c# Delegate 例子

本文介绍了一个使用C#实现的程序,该程序通过事件处理机制接收并处理用户输入的字符,过滤非字母字符,并将处理后的字符分别输出到控制台、执行特定操作和记录到文件中。

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

 

using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace ConsoleApplication2
{
    class MyDelegateTest
    {
        public class KeyInputClass
        {
            public delegate void KeyInEventHander(string str);
            public event KeyInEventHander KeyinEvent;
            public void KeyInput()
            {
                Console.WriteLine("please keyin:");
                string str = Console.ReadLine();
                str = Regex.Replace(str, "[^a-z]", "");
                KeyinEvent(str);
                //string str = Console.ReadKey().ToString();
                //Match s = Regex.Match(str,"[a-z]");
                //if(s.Success)
                //{
                    //KeyinEvent(str);
                //}
            }
        }

        public class KeyOutputClass
        {
            public void KeyOutput(string str)
            {
                Console.WriteLine("Output {0} if key is lower-case",str);
             
            }
        }

        public class KeylogClass
        {
            public void Keylog(string str)
            {
                if (!File.Exists("c:\\logtest.txt"))
                {
                    Console.WriteLine("create File file:c:\\logtest.txt ,please retry");
                    File.CreateText("c:\\logtest.txt");
                    return;
                }
                Console.WriteLine("Add log string({0}) to file:c:\\logtest.txt,if no exist file,will create it",str);
                Console.WriteLine("Input Enter-key quit");
               
               
                StreamWriter sw = new StreamWriter(@"C:\\logtest.txt", true);
                sw.WriteLine(str);
                sw.Close();   
            }
        }

        static void Main()
        {
            KeyInputClass  ki = new KeyInputClass();
            KeyOutputClass ko = new KeyOutputClass();
            KeylogClass    kl = new KeylogClass();
            ki.KeyinEvent+=new KeyInputClass.KeyInEventHander(ko.KeyOutput);
            ki.KeyinEvent+=new KeyInputClass.KeyInEventHander(kl.Keylog);
            ki.KeyInput();
            Console.Read();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值