C# interface cannot contain operators

泄露秘密 提交于 2019-11-29 15:56:21

问题


Can anyone please explain why C# interfaces are not allowed to contain operators?

Thanks.


回答1:


C# operators have to be static. Interfaces, by definition, apply to instances. There is no mechanism to require a type to implement static methods.




回答2:


You can't define operators on interfaces because a class can implement multiple interfaces. Imagine if this code were possible:

static class Fooness {
  public static operator==(IFoo l, IFoo r) { ... }
}
static class Barness {
  public static operator==(IBar l, IBar r) { ... }
}

public class Foobar : IFoo, IBar { ... }

Which == implementation should prevail if used on instances of Foobar? (And before you answer, imagine if IFoo/Fooness come from one DLL and IBar/Barness comes from another).

Even if you could somehow resolve that ambiguity, we should ask ourselves whether it would even be a good idea. I hope the above shows that with operator== it's a seriously bad idea. The author of the per-interface == operator presumes that the only important aspects of an object when it comes to comparison are those encompassed by the interface. Sometimes that can be true, but it's not generally true.

That's why it's prudent to only use operators on sealed classes. Only then can you be sure that your operator knows enough about the object to work correctly.



来源:https://stackoverflow.com/questions/6603940/c-sharp-interface-cannot-contain-operators

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!