我刚刚意识到我不懂任何 C#。
在委托(delegate)实例上使用 +=
和 Delegate.Combine
有什么区别吗?
例如
public delegate void Printer(string s);
public class Program
{
public static void Main(string[] args)
{
Printer printer = new Printer((s) => { Console.WriteLine(s); });
// is it wrong to use this += operator
// on the delegate instance printer?
printer += s => {};
// And is this somewhat holier than the previous one?
// why?
Delegate.Combine(printer, new Printer((s) => {});
}
}
我问这个问题是因为serge karalenka 在此线程上的回答似乎暗示了这个问题:https://stackoverflow.com/a/15183049/303685
最佳答案
不好吗?一点都不。事实上,我更喜欢它。
使用它而不是 Combine()
的一个很好的理由是,它不太可能犯您在示例中犯的错误:未能将结果实际分配给某物。 IE。请注意,Combine()
方法返回新的委托(delegate)实例。与 string
一样,委托(delegate)是不可变的,所有修改都涉及创建新实例。
虽然 +
运算符可能会犯同样的错误,但大多数人不会将代码编写为 printer + (s => {})
甚至如果他们这样做了,那么在那种情况下很明显表达式的结果没有分配给任何东西。更惯用的 +=
当然完全不受这个问题的影响。 :)
关于c# - 在委托(delegate)上使用 += 运算符不好吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28391345/