首页 > 编程语言 >C# 委托

C# 委托

时间:2022-11-09 11:46:41浏览次数:34  
标签:return 委托 C# void func 方法 public

委托初始

委托是一个引用类型,其实是一个类(当成类来看待),保存的是方法的指针,当我们调用委托的时候这个方法就立即被执行。

委托的关键字:delegate

创建委托:

//定义委托
delegate void HelloDelegate(string mag);

class Program
{
    static void Main(string[]args)
    {
        //创建委托实列   传入委托方法,方法需带有和委托定义相同的参数和返回值
        HelloDelegate helloDelegate = new HelloDelegate(Hello);
        //调用委托
        helloDelegate("这是委托");//调用委托 传入参数
    }
    
    public static void Hello(string str)
    {
        Console.WriteLine(str);
    }

}

泛型委托

委托当作为一个类来看待 是可以写为一个泛型类的

namespace CsharpAdvancedDelegate
{
    //泛型委托声明
    delegate void GenericDelegate<T>(T t);
    public class GenericDelegate
    {
        public static void InvokeDelegate()
        {
            //示例化泛型委托
            GenericDelegate<string>genericDelegate = new GenericDelegate<string>(Method1);
            genericDelegate("我是泛型委托1");
            GenericDelegate<int>genericDelegate = new GenericDelegate<int>(Method2);
            genericDelegate(2);
            
            
        }
        
        public static void Method1(string str)
        {
            Console.WriteLine(str);
        }
        public static void Method2(int num)
        {
            Console.WriteLine("我是泛型委托2"+num);
        }
        public static string Method3(string str)
        {
            return str;
        }
        
        
      
        
    }
}

这种泛型的委托,官方也是提供了不带返回值的Action版本和带返回值的Func版本

//官方Action版本的委托使用方法
Action<string>action = new Action<string>(Method1);
action("我是泛型委托1");
//官方Func版本 带返回值
Func<string,string> func = new Func<string,string>(Method3);
func("我是带返回值Func委托");

多播委托

每一个委托都是继承自MulticastDelegate,也就是每一个都是多播委托

委托的方法引用列表可以保存多个方法,可以使用+=来生成委托方法链,连接方法,也可以使用-=来去除方法。

public void MethodTest()
{
    Console.WriteLine("我是方法MethodTest()");
}
public void MethodTest2()
{
    Console.WriteLine("我是方法MethodTest()2");
}
public void MethodTest3()
{
    Console.WriteLine("我是方法MethodTest()3");
}

//定义委托 连接方法形成委托链
Action action = MethodTest;
action+=MethodTest2;
action+=MethodTest3;
action();

匿名函数的使用

Lambda表达式的使用,使委变得更加简洁不用再去实现委托方法,使用匿名函数进行替代

带返回值的多播委托 只返回最后一个方法的值

Func<string> func = ()=>{return "我是Lambda";};
func+=()=>{return "我是func1";};
func+=()=>{return "我是func2";};
func+=()=>{return "我是func3";};
string result = func();
Console.WriteLine(result);
//最后只会输出"我是func3"

使用匿名函数后 -=将不再生效,匿名函数会直接生成一个新的方法,不会和之前的方法相同,导致去除委托链失效,存在需要去除的方法时 依旧使用定义出来的函数方法

Func<string> func = ()=>{return "我是Lambda";};
func+=()=>{return "我是func1";};
func+=()=>{return "我是func2";};
func+=()=>{return "我是func3";};
func-=()=>{return "我是func3";};//此处会生成一个新得匿名函数 -=后不会影响上面得func3 导致去除失败
string result = func();
Console.WriteLine(result);

标签:return,委托,C#,void,func,方法,public
From: https://www.cnblogs.com/ChenRicardo/p/16873107.html

相关文章