c#高级概念

8月 28, 2022 185点热度 0人点赞 0条评论

1委托

public delegate int MyDelegate (string s);
完整写法:
MyDelegate md=new MyDelegate();
md.Invoke(xxx) 

关键字可以省略第二种写法:

MyDelegate md=funct1; 
md(xxx);
我感觉就是动态调用方法,把方法名作为 参数传递进去调用
前提:返回值类型要一样,参数也要一样


实例
using System;
using System.IO;

namespace DelegateAppl
{
   class PrintString
   {
      static FileStream fs;
      static StreamWriter sw;
      // 委托声明
      public delegate void printString(string s);

      // 该方法打印到控制台
      public static void WriteToScreen(string str)
      {
         Console.WriteLine("The String is: {0}", str);
      }
      // 该方法打印到文件
      public static void WriteToFile(string s)
      {
         fs = new FileStream("c:\\message.txt", FileMode.Append, FileAccess.Write);
         sw = new StreamWriter(fs);
         sw.WriteLine(s);
         sw.Flush();
         sw.Close();
         fs.Close();
      }
      // 该方法把委托作为参数,并使用它调用方法
      public static void sendString(printString ps)
      {
         ps("Hello World");
      }
      static void Main(string[] args)
      {
         printString ps1 = new printString(WriteToScreen);
         printString ps2 = new printString(WriteToFile);
         sendString(ps1);
         sendString(ps2);
         Console.ReadKey();
      }
   }
}


2箭头函数
=》 取代 { }
static int b(int x) => x * x;

用于 只返回一个值

李 锋

这个人很懒,什么都没留下

文章评论