gpt4 book ai didi

c# - 初始化 C# 委托(delegate)的 "correct"方法是什么?

转载 作者:太空狗 更新时间:2023-10-29 18:19:21 31 4
gpt4 key购买 nike

C# 委托(delegate)对我来说一直很难掌握,所以我很高兴偶然发现 logicchild's article on The Code Project web site titled "C# Delegates: Step by Step" .他有一种非常简洁的方式来解释 C# 委托(delegate),我可以向您推荐它。但是,在尝试这些示例时,我发现有两种初始化委托(delegate)的方法,主要是:

    //create a new instance of the delegate class
CalculationHandler sumHandler1 = new CalculationHandler(math.Sum);
//invoke the delegate
int result = sumHandler1(8, 9);
Console.WriteLine("Result 1 is: " + result);

    CalculationHandler sumHandler2 = math.Sum;
//invoke the delegate
int result = sumHandler2(8, 9);
Console.WriteLine("Result 2 is: " + result);

数学类定义为

public class math
{
public int Sum(int x, int y)
{
return x + y;
}
}

那么哪个是“正确”的方式,为什么?

最佳答案

它们都是正确的,但是 method group conversion ,这是 2.0 (IIRC) 中添加的第二个选项。 IE。如果您使用的是旧版本的编译器,则需要使用第一个选项。否则额外的打字真的是多余的。

关于c# - 初始化 C# 委托(delegate)的 "correct"方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3750843/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com