Sorry, your browser cannot access this site
This page requires browser support (enable) JavaScript
Learn more >

C# 委托


  • 委托的概念

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

  • 常见委托的使用

    1
    2
    3
    delegate int MethodDelegate(int x,inty);

    MethodDelegate method = new MethodDelegate(function_name);
    1
    MethodDelegate method = function_name;

    将对应的函数名放入function_name位置,函数的签名需要和委托声明的一样。

    1
    2
    3
    4
    5
    6
    7
    8
    //使用匿名方法
    MyDelegate myDelegate = delegate(int x, int y)
    {
    return x + y;
    };

    //使用Lambda表达式
    MyDelegate myDelegateLambda = (int x, int y) => { return x + y; };
  • 其他委托的分类

    1.Action

    Action作为一种反省委托,不具备返回值

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    static void Main(string[] args)
    {
    Test<string>(Action,"Hello World!");
    Test<int>(Action, 1000);
    Test<string>(p => { Console.WriteLine("{0}", p); }, "Hello World");
    //使用Lambda表达式定义委托
    Console.ReadKey();
    }
    public static void Test<T>(Action<T> action, T p)
    {
    Action(p);
    }
    private static void Action(string s)
    {
    Console.WriteLine(s);
    }
    private static void Action(int s)
    {
    Console.WriteLine(s);
    }

    2.Func

    Func是返回值的泛型委托

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    static void Main(string[] args)
    {
    Console.WriteLine(Test<int,int>(Fun,100,200));
    Console.ReadKey();
    }
    public static int Test<T1, T2>(Func<T1, T2, int> func, T1 a, T2 b)
    {
    return func(a, b);
    }
    private static int Fun(int a, int b)
    {
    return a + b;
    }

    3.predicate

    predicate是返回值bool的泛型委托

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    public delegate int MethodDelegate(int x, int y);
    private static MethodDelegate method;
    static void Main(string[] args)
    {
    method = new MethodDelegate(Add);
    Console.WriteLine(method(10,20));
    Console.ReadKey();
    }

    private static int Add(int x, int y)
    {
    return x + y;
    }
  • 委托的好处

    1. 相当于用方法作为另一方法参数(类似于C的函数指针)

    2. 在两个不能直接调用的方法中作为桥梁,如:在多线程中的跨线程的方法调用就得用委托

    3. 当不知道方法具体实现什么时使用委托,如:事件中使用委托

  • 注意事项与特点

     1. 虽然委托的定义有点像方法的声明,但是委托是属于类的层面。

     2. 委托类似于C++的函数指针,但是它是类型安全的

     3.委托允许将方法作为参数进行传递。

     4. Delegate至少0个参数,至多32个参数,可以无返回值,也可以指定返回值类型

     5. Func可以接受0个至16个传入参数,必须具有返回值

     6. Action可以接受0个至16个传入参数,无返回值

     7 Predicate只能接受一个传入参数,返回值为bool类型

相关博客:

分分钟用上C#中的委托和事件 (该文学习将委托是事件结合,从而实现一个对象发送指令,其他的对象根据不同指令进行自己的操作的功能)

Thanks to Danny Chen

评论