c# - 委托(delegate)如何运作

标签 c# visual-studio-2012 delegates

使用 C#、.Net Framework 4.5、Visual Studio 2012

经过一些theory尝试在 C# 中创建一些委托(delegate)。

当前创建下一个代码

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;
    }
    }
}

还有花药类

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

结果如下

My result

所以问题 - 为什么委托(delegate)MyDelegate 不起作用而通用变体- 起作用?我哪里错了。

还有另一个问题 - 我可以调用显示的示例方法,如下所示

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

使用委托(delegate)时我有什么优势?或者这只是一个变体,我如何使用委托(delegate)和“全权”,我可以看到什么时候可以尝试使用兰巴扩展和事件? (刚刚读到本章 - 尚未阅读 - 想更好地理解委托(delegate))。

最佳答案

要回答你的第一个问题,你的委托(delegate)没有工作,因为你从未调用过它。您刚刚在此处创建了它的一个实例:

MyDelegate myD;
myD = new MyDelegate(TestMethod);

但是您的程序中没有任何地方实际调用myD。尝试这样调用它:

MyDelegate myD;
myD = new MyDelegate(TestMethod);
myD();

为了回答你的第二个问题,使用委托(delegate)的主要优点是你可以引用一个方法而无需立即调用它。例如,假设您想要将一个方法传递给另一个函数以进行一些额外的处理:

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

Repeat(NewOne.Hello, 5);

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

关于c# - 委托(delegate)如何运作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19987557/

相关文章:

c# - 属性(property)已由 'ListView' 注册

c# - ReSharper "Cannot resolve symbol"即使在项目构建时

visual-studio-2012 - Visual Studio - Step over 禁用自身

c# - 创建一个具有其他两个对象的所有属性的对象?

c# - 如何为 Web API Controller 编写单元测试

C# html 敏捷包,捕获重定向

jquery - jquery live 的替代方案可以工作

c# - 是否可以从委托(delegate)中别名/引用委托(delegate)?

iOS TTTAttributedLabel 委托(delegate) didSelectLinkWithURL 没有被调用

c# - linq 从 ArrayList 解析整数