AI智能
改变未来

c#入门第十六课


线程

static void Test1(){Console.WriteLine(\"Test1\");}static void Test2(){Console.WriteLine(\"Test2\");}static void Main(string[] args){//创建子线程ThreadStart ts1 = new ThreadStart(Test1);Thread thread1 = new Thread(ts1);ThreadStart ts2 = new ThreadStart(Test2);Thread thread2 = new Thread(ts2);//开始线程thread1.Start();thread2.Start();Console.WriteLine(\"Main\");}

委托

class DelegateTest{//委托 新的类型public delegate void CalcHandler(int a, int b);public DelegateTest(){/*CalcHandler calcHandler = new CalcHandler(Add);calcHandler(3, 4);calcHandler = new CalcHandler(Sub);calcHandler(4, 3);*///CalcHandler calcHandler = Add;//委托链CalcHandler calcHandler = Add;calcHandler += Sub;calcHandler(3, 4);}public void Add(int a,int b){Console.WriteLine(a+b);}public void Sub(int a, int b){Console.WriteLine(a - b);}}class Timer{//委托public delegate void TimerHandler();public Timer(int time,TimerHandler timerHandler){Thread.Sleep(time * 1000);if (timerHandler != null){timerHandler();}}}class Person{public Person(){//创建一个闹钟Timer.TimerHandler timerHandler = new Timer.TimerHandler(Eat);Timer timer = new Timer(3, timerHandler);}public void Eat(){Console.WriteLine(\"吃饭\");}}class Game{static void Main(string[] args){//new DelegateTest();new Person();}}

匿名函数

匿名函数是没有函数名的函数,仅限委托绑定

Timer timer = new Timer(3,delegate(int  time){Console.WriteLine(time+\"分钟过去了,该上学了\");});//LambdaTimer timer = new Timer(3, (int time) => {Console.WriteLine(time + \"分钟过去了,该上学了\");});

事件

public TimerHandler timerHandler;public event TimerHandler TimerEvent;

timer.timerHandler = Eat;
timer.TimerEvent += Eat;
委托链可以等于,事件不可以等于

系统封装

//public Timer(int time,Action timerHandler)
//public Timer(int time,Func timerHandler)

正则表达式

static void Main(string[] args){string input = \"abcdef@163.com\";string pattern = @\"^\\w{3,10}@\\w+\\.\\w+$\";input = \"123-456789-123\";pattern = @\"\\d{3}-\\d{3}\";Regex regex = new Regex(pattern);//Console.WriteLine(regex.IsMatch(input));//Match match = regex.Match(input);//Console.WriteLine(match.Value);//多匹配foreach(Match match in regex.Matches(input)){Console.WriteLine(match.Value);}}

IO

/*StreamWriter sw = new StreamWriter(\"test.txt\");sw.Write(\"asdasf\");sw.Close();*///using (StreamWriter sw = new StreamWriter(\"test.txt\"))//{//    sw.Write(\"asdasf\");//}StreamReader sr = new StreamReader(\"test.txt\");string str = sr.ReadToEnd();Console.WriteLine(str);sr.Close();
赞(0) 打赏
未经允许不得转载:爱站程序员基地 » c#入门第十六课