1. 程式人生 > >c# Delegate 例子

c# Delegate 例子

 

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();
        }
    }
}