c#10进阶语法 (2)

181 阅读2分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第3天,点击查看活动详情

前言

我们继续讲一讲C#进阶语法,今天小编讲的是委托、IEnumerable类型以及扩展方法,这是.netcore很重要的基础,也是学习它的必经之路,大家就跟着我的步伐一起来看一看吧。

委托

老样子,解释在代码的注释里,方便理解

委托:也是一种类型,特殊类型,初始化需要一个方法的支持,委托是记录方法的一种类型,调用委托也就是调用委托实例化委托的方法。

定义方式:delegate + 返回值 + 委托名称+ (参数类型,参数名称)

一般都是通过方法写委托

1.自定义委托

delegate void HelloDelegate(string msg) //定义委托
    
 main函数:
{
    //定义委托方法,返回值类型和参数要一样(包括参数类型,顺序,个数)
 public static void Hell0(string msg){
    Console.WriteLine("你好,我是委托");
}
    
    //委托初始化(需要一个和签名委托一样的方法来实例化,只需要写方法名)
    HelloDelegate hello = new HelloDelegate(Hello);
    
    //调用
    hello.Invoke("");//调用委托也就是调用委托实例化委托的方法。(也可以不要写INVOKE)
}
​

2.泛型委托

delegate void AddDelegate<T>(T a, T b);
​
​
public void AddInt(int a, int b){
    
}
​
public void AddDouble(double a, double b){
    
}
​
AddDelegate<int> addDelegate = new AddDelegate(AddInt)

3.预定义委托

官方以及封装好定义,即使用Action(无返回值),Func(有返回值)

//无返回值
Action<string,int> action = new Action<string,int>(show);
​
action("aa",1)
​
    
 //有返回值
    Func<string> func1 = new Func<string>(show2);
  console.writeline(func1());
​
Func<int,int> func2 = new Func<int,int>(show3);
  int num = func2(5);
  console.writeline(num);
​
public static void show(string a, int b){
    console.writeline(a);
}
​
public static string show2(string a){
   return "aa";
}
​
public static string show3(int g){
   return g;
}

4.Lambda委托

//第一种
Action<string> action = new Action<string>(delegate(string msg)=>{
    console.writeline(msg)
})
    
action("泛型委托,使用匿名函数")
    
    
//第二种
Action<string> action1 = new Action<string>((string msg)=>{
    console.writeline(msg)
})
    
action1("泛型委托,使用匿名函数")
    
 //第三种
Action<string> action1 = new Action<string>( msg=>console.writeline(msg)   
)
    
action1("泛型委托,使用匿名函数")

其实也可以直接实例:

Action<string> action1 =  msg=>console.writeline(msg) 

IEnumerable

1.IEnumerable可枚举类型 --可迭代类型

2.IEnumerator枚举器

3.Enum枚举

主要一个类型实现了IEnumerable接口,就可以对他进行遍历。

yield关键词,它是一个迭代器,相当于实现了IEnumerator枚举器。

class Student :IEnumerable
{
    public int Id{get;set;}
    
    public IEnumerator GetEumerator(){
        yield return "aaa"
    }
}

扩展方法

静态类里的静态方法,参数列表中最前面加个this+要扩展的类型

  public static class ToMd5Helper
    {
        public static String ToMd5( this string str)
        {
            using(var md5 = MD5.Create())
        {
            var result = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
            var strResult = BitConverter.ToString(result);
                string result3 = strResult.Replace("-", "");
                return strResult;
​
        }
           
​
        
        }
    };
总结:这就是今天我们的内容,其中委托是比较重要的,在后面会经常用到,大家也多多理解,打好扎实的基础。哈哈哈,还是那句话,一步步来,加油!