C#事件演示程序4)——一段经典的代码

本文通过一个简单的 C# 代码示例介绍了如何使用事件和委托来处理按键输入。示例展示了如何定义和触发事件,以及如何注册多个事件处理器来响应同一个事件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 
using System;

public class KeyEventArgs : EventArgs
{
    
public char ch;
}

public delegate void KeyHandler(object source,KeyEventArgs arg);

public class KeyEvent
{
    
public event KeyHandler KeyPress;

    
public void OnKeyPress(char key)
    {
        KeyEventArgs k 
= new KeyEventArgs();

        
if (KeyPress != null)
        {
            k.ch 
= key;
            KeyPress(
this, k);
        }
    }
}

public class ProcessKey
{
    
public void Process(object source, KeyEventArgs arg)
    {
        Console.WriteLine(
"Received keystroke:"+arg.ch);
    }
}

public class CountKeys
{
    
public int count = 0;
    
public void Process(object source, KeyEventArgs arg)
    {
        count
++;
        
//Console.WriteLine(count.ToString());
    }
}

public class KeyEventDemo
{
    
static void Main(string[] args)
    {
        KeyEvent kevt 
= new KeyEvent();
        ProcessKey pk 
= new ProcessKey();
        CountKeys ck 
= new CountKeys();

        
char ch;
        kevt.KeyPress 
+= new KeyHandler(pk.Process);
        kevt.KeyPress 
+= new KeyHandler(ck.Process);
        Console.WriteLine(
"Enter some characters."+"Enter a period to stop.");

        
do
        {
            ch 
= (char)Console.Read();
            kevt.OnKeyPress(ch);
        }
        
while (ch != '.');

        Console.WriteLine(ck.count 
+ "keys pressed.");
    }
}

   
好的,下面是一个简单的C#控制台应用程序示例。此项目旨在模拟图书馆管理系统的一部分功能——管理书籍信息(添加、删除和列出所有书籍)。我们将展示如何使用类来组织代码,并通过基本的用户交互来进行操作。 ### 图书馆管理系统 - 控制台版 #### 1. 创建图书实体类 首先我们需要定义一个表示“书”的类 `Book` ,它包括一些基本信息如标题、作者等。 ```csharp using System; namespace LibraryManagementSystem { public class Book { public string Title { get; set; } public string Author { get; set; } public Book(string title, string author) { Title = title; Author = author; } override public string ToString() { return $"《{Title}》 by {Author}"; } } } ``` #### 2. 构建核心业务逻辑 —— 图书库类 接下来构建我们的 “Library” 类用于存储所有的书籍并且提供增删查等功能。 ```csharp using System; using System.Collections.Generic; using System.Linq; namespace LibraryManagementSystem { public class Library { private List<Book> books = new List<Book>(); /// <summary> /// 添加一本书到图书馆. /// </summary> public void AddBook(Book book) { books.Add(book); Console.WriteLine($"{book.Title} 已成功加入图书馆."); } /// <summary> /// 删除指定编号位置的一本书. /// </summary> /// <param name="index">书本在列表中的序号</param> public bool RemoveBook(int index) { if (index >= 0 && index < books.Count) { var removedBook = books[index]; books.RemoveAt(index); Console.WriteLine($"已移除: {removedBook}"); return true; } else { Console.WriteLine("无效的位置!"); return false; } } /// <summary> /// 列出当前库存的所有书籍. /// </summary> public void ListBooks() { if (!books.Any()) { Console.WriteLine("目前没有藏书。\n"); return; } foreach (var book in books.Select((value, i) => new { i, value })) { Console.WriteLine($"{book.i + 1}. {book.value}\n"); } } /// <summary> /// 查找特定名称的书. /// </summary> public IEnumerable<Book> SearchByTitle(string keyword) { return from b in books where b.Title.Contains(keyword) select b; } } } ``` #### 3. 主程序入口及菜单驱动循环 最后编写主函数 `Program.cs` 来引导整个应用流程并与用户互动: ```csharp using System; namespace LibraryManagementSystem { internal class Program { static void Main(string[] args) { Library myLibrary = new Library(); while (true) { PrintMenu(); switch(Console.ReadLine().ToLower()) { case "a": // 添加新书 AddNewBook(myLibrary); break; case "r": // 移除现有书目 RemoveExistingBook(myLibrary); break; case "l": // 显示全部收藏 ShowAllBooks(myLibrary); break; case "s": // 搜索某一本具体的书 SearchForABook(myLibrary); break; default: Environment.Exit(0); // 结束程序 break; } } } private static void PrintMenu() { Console.Clear(); Console.WriteLine("--- 菜单 ---\na: 添加新书\nr: 移除已有书目\nl: 展示所有藏书\ns: 查询书籍\nq: 退出"); } private static void AddNewBook(Library library) { try { Console.Write("\nEnter the title of the book you wish to add:\t"); string title = Console.ReadLine(); Console.Write("Enter its author's name:\t\t"); string authorName = Console.ReadLine(); Book newBook = new Book(title, authorName); library.AddBook(newBook); } catch(Exception ex) { Console.WriteLine(ex.Message); } } private static void RemoveExistingBook(Library library) { Console.Write("请输入你要删除哪本书籍对应的数字:"); string inputIndexStr = Console.ReadLine(); int selectedIndex; if(Int32.TryParse(inputIndexStr, out selectedIndex)) { selectedIndex--; // 用户输入的是从1开始计数的人类友好数字 library.RemoveBook(selectedIndex); } else { Console.WriteLine("非法输入,请重新选择正确的选项。\n"); } } private static void ShowAllBooks(Library library) { library.ListBooks(); PauseAfterAction(); } private static void SearchForABook(Library library) { Console.Write("输入你想查找的关键字:"); string keyword = Console.ReadLine(); var searchResults = library.SearchByTitle(keyword).ToList(); if(searchResults.Any()) { Console.WriteLine($"\n找到与'{keyword}'相关的书籍:"); foreach(var result in searchResults) { Console.WriteLine(result.ToString()); } } else { Console.WriteLine($"未发现有关 '{keyword}' 的记录..."); } PauseAfterAction(); } private static void PauseAfterAction() => Console.ReadKey(intercept:true); } } ``` 这段完整的代码实现了基础的功能模块:我们可以向系统中增加新的书籍条目,也可以从中检索、浏览甚至删除现有的记录。当然实际的应用会比这复杂得多,但是这个案例已经足够演示面向对象的设计思想以及良好的结构化的编码风格了!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值