c# - 在委托(delegate)上使用 += 运算符不好吗?

标签 c#

我刚刚意识到我不懂任何 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/

相关文章:

c# - 如何在 ASP.Net 页面上将 List<string> 的 URL 显示为超链接(C#)

c# - 如何创建 Entity Framework 模型第一个关联表?

c# - 同时调用 ASP.NET 托管的 WCF 服务时出现 Entity Framework 错误

c# - C#中如何跨线程调用BindingList<T>

c# - 从交换服务器检索用户的详细信息

c# - 了解 WMI 对象路径格式

c# - 列出连接到单个 LAN 的所有计算机的 IP 地址

c# - Entity Framework ,按日/周/月在日期时间工作

c# - 处理在不同线程中读取的 TCP Socket 数据

c# - 极长的 Rx 事件链