委派它是如何工作的

gbk*_*gbk 2 c# delegates visual-studio-2012

使用C#,.Net Framework 4.5,visual Studio 2012

经过一些理论尝试在C#中创建一些委托.

目前创建下一个代码

namespace SimpleCSharpApp
{
public delegate void MyDelegate();
class Program
{   
    private static string name;
    static void Main(string[] args)
    {
        //my simple delegate
        Console.WriteLine("Enter your name");
        name = Console.ReadLine().ToString();
        MyDelegate myD;
        myD = new MyDelegate(TestMethod);

        //Generic delegate
        Func<Int32, Int32, Int32> myDel = new Func<Int32, Int32, Int32>(Add);
        Int32 sum = myDel(12, 33);
        Console.WriteLine(sum);
        Console.ReadLine();

        //call static method from another class
        myD = new MyDelegate(NewOne.Hello);
    }
    public static void TestMethod()
    {
        Console.WriteLine("Hello {0}", name);
    }
    public static Int32 Add(Int32 a, Int32 b)
    {
        return a + b;
    }
    }
}
Run Code Online (Sandbox Code Playgroud)

和花药班

namespace SimpleCSharpApp
{
 sealed class NewOne
{
    static public void Hello()
    {
        Console.WriteLine("I'm method from another class");
    }
}
}
Run Code Online (Sandbox Code Playgroud)

结果得到了下一个

我的结果

所以问题 - 为什么代表MyDelegate不工作和通用变体 - 工作?哪里我错了.

另一个问题 - 我可以调用这样的显示样本方法

        //calling method
        Console.WriteLine("Enter your name");
        name = Console.ReadLine().ToString();
        TestMethod();
        //from another class
        NewOne.Hello();
Run Code Online (Sandbox Code Playgroud)

我在使用代表时获得的优势是什么?或者它只是一个变种我如何使用委托和"全功率"我可以看到何时可以尝试lamba扩展和事件?(刚刚进入本章 - 尚未阅读 - 想要更好地理解代表).

p.s*_*w.g 5

要回答您的第一个问题,您的代表无法工作,因为您从未调用它.你刚刚在这里创建了一个实例:

MyDelegate myD;
myD = new MyDelegate(TestMethod);
Run Code Online (Sandbox Code Playgroud)

但是你的程序中没有任何地方可以实际调用myD.试着像这样调用它:

MyDelegate myD;
myD = new MyDelegate(TestMethod);
myD();
Run Code Online (Sandbox Code Playgroud)

要回答第二个问题,使用委托的主要优点是您可以在不立即调用方法的情况下引用方法.例如,假设您要将方法传递给另一个函数以进行一些额外的处理:

private void Repeat(MyDelegate method, int times)
{
    for (int i = 0; i < times; i++)
        method();
}

Repeat(NewOne.Hello, 5);
Run Code Online (Sandbox Code Playgroud)

您允许该Repeat方法控制NewOne.Hello调用的方式和时间,而无需Repeat知道在编译时需要调用哪个方法.这个想法是一些编程技术的核心(参见功能编程).你可能已经熟悉的一个重要的是Linq,它使用委托以高效和优雅的方式操作集合.