在C#中委托模式与委托关键字

R4j*_*R4j 9 c# delegates design-patterns

来自MSDN doc:

委托是一种安全封装方法的类型,类似于C和C++中的函数指针.与C函数指针不同,委托是面向对象的,类型安全的和安全的.

我知道它是什么以及如何使用它.但是我想知道它是否是基于代理模式编写的(我知道)(来自维基百科).
他们之间有什么区别?

ie.*_*ie. 6

在实现委托模式时,C#(非模式)委托可能很有用,只需通过我的更改来查看维基百科中的委托模式实现:

//NOTE: this is just a sample, not a suggestion to do it in such way

public interface I
{
    void F();
    void G();
}

public static class A
{
    public static void F() { System.Console.WriteLine("A: doing F()"); }
    public static void G() { System.Console.WriteLine("A: doing G()"); }
}

public static class B
{
    public static void F() { System.Console.WriteLine("B: doing F()"); }
    public static void G() { System.Console.WriteLine("B: doing G()"); }
}

public class C : I
{
    // delegation 
    Action iF = A.F;
    Action iG = A.G;

    public void F() { iF(); }
    public void G() { iG(); }

    // normal attributes
    public void ToA() { iF = A.F; iG = A.G; }
    public void ToB() { iF = B.F; iG = B.G; }
}

public class Program
{
    public static void Main()
    {
        C c = new C();
        c.F();     // output: A: doing F()
        c.G();     // output: A: doing G()
        c.ToB();
        c.F();     // output: B: doing F()
        c.G();     // output: B: doing G()
    }
}
Run Code Online (Sandbox Code Playgroud)

委托可能在这里有用,但不是因为它被引入.你应该在低层建筑而不是模式上看待它.在具有事件的对中,它可用于实现发布者/订阅者(观察者)模式 - 只需查看本文,或者它有时可以帮助您实现访问者模式 - 这在LINQ中被积极使用:

public void Linq1() 
{ 
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 

    // n => n < 5 is lambda function, creates a delegate here
    var lowNums = numbers.Where(n => n < 5); 

    Console.WriteLine("Numbers < 5:"); 
    foreach (var x in lowNums) 
    { 
        Console.WriteLine(x); 
    } 
} 
Run Code Online (Sandbox Code Playgroud)

总结一下:语言委托不是模式本身,它只是允许您将函数作为第一类对象来操作.