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

C#委托

作者:互联网

定义

委托是一个类,它定义了方法的类型,使得可以将方法当作另一个方法的参数来进行传递,这种将方法动态地赋给参数的做法,可以避免在程序中大量使用If-Else(Switch)语句,同时使得程序具有更好的可扩展性。

所以,当会有大量重复的方法时,你可以使用委托。最重要的是,首先它是一个类,类平时怎使用的呢,声明、实例化、调用方法,谨记这一点

使用

1.无参数无返回值

//声明委托
delegate void MyDelegate();
static void Main(string[] args)
{
    //实例化委托
    MyDelegate myDelegate = A;
    //调用委托
    myDelegate();
    Console.ReadKey();
}

//方法
static void A()
{
    Console.Write("A");
}

2.有参数有返回值

//声明一个有参数有返回值的委托
delegate string MyDelegate(string a);
static void Main(string[] args)
{
    MyDelegate myDelegate = A;
    string a = myDelegate("10");
    Console.Write(a);
    Console.ReadKey();
}
//要委托的方法 参数、类型必须同声明的委托相同
static string A(string a)
{
    return a;
}

3.绑定

delegate void MyDelegate(string a);
static void Main(string[] args)
{
    MyDelegate myDelegate = A;
    // += 绑定额外方法,依次执行  同理 -=解绑
    myDelegate += B;
    myDelegate("10");
    Console.ReadKey();
}
static void A(string a)
{
    Console.Write(a);
}
static void B(string b)
{
    Console.Write(b);
}

4.扩展 当你有大量重复方法时,你就可以使用委托

delegate string MyDelegate(string a);
static void Main(string[] args)
{
    MyDelegate myDelegateA = A;
    MyDelegate myDelegateB = B;

    string resultA = AB(myDelegateA, "10");
    string resultB = AB(myDelegateB, "20");

    Console.WriteLine(resultA + resultB);
    Console.ReadKey();
}
static string A(string a)
{
    Console.WriteLine(a);
    return a;

}
static string B(string b)
{
    Console.WriteLine(b);
    return b;
}

//定义一个带有委托参数的方法
static string AB(MyDelegate m, string a)
{
    return m(a);
}

 

标签:Console,string,委托,C#,void,static,MyDelegate,myDelegate
来源: https://blog.csdn.net/m0_37639018/article/details/96601132