简体   繁体   English

在C#中使用Delegate的推荐方法

[英]The recommended way to use the Delegate in C#

If the delegate is just a reference point to a method,then I think I should not use the delegate in the object-way (creating an instance of the delegate type). 如果委托只是方法的引用点,那么我认为我不应该以对象方式使用委托(创建委托类型的实例)。

This is the first snippet: 这是第一个片段:

public delegate void Del1(string message);
public class Test
{
  public static void Method1(string message)
  {
     System.Console.WriteLine(message);
  }
}
Test test new Test();
del1 handler=new del1(Test.Method1);
handler("Hello world!");

This is the second snippet: 这是第二个片段:

public delegate void Del2(string message);
public static void Method2(string message)
{
    System.Console.WriteLine(message);
}
Del2 handler = Method2;
handler("Hello World");

The first way is more general for me. 第一种方式对我来说更为一般。

The second way doesn't have to create an instance, is it just because the method it delegate is static? 第二种方式不必创建实例,是因为它委托的方法是静态的吗?

If Yes, which one is more general in concept? 如果是,哪一个概念更通用?

Both code snippets are identical. 两个代码段都是相同的。 The second is merely allowing the compiler to automatically infer the delegate type of the method group, instead of providing it explicitly. 第二个是仅允许编译器自动推断方法组的委托类型,而不是显式提供它。 You're creating an instance of a delegate in both cases. 在这两种情况下,您都在创建委托实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM