【发布时间】:2011-08-19 19:39:39
【问题描述】:
我正在尝试像这样实现一个通用运算符:
class Foo
{
public static T operator +<T>(T a, T b)
{
// Do something with a and b that makes sense for operator + here
}
}
我真正想做的是优雅地处理继承。在 Foo 中使用标准运算符 +,其中 T 是“Foo”,如果任何人从 Foo 派生(例如 Bar 继承 Foo),那么 Bar + Bar 操作仍将返回 Foo。我希望用通用运算符 + 来解决这个问题,但我只是得到了上述(在
有没有办法制作泛型运算符?
【问题讨论】:
-
一个可行(尽管对程序员不太友好)的解决方法可能是一个采用通用参数的命名方法:
public static T Add<T>(T a, T b) { //Implementation goes here }。这可以像Foo x = new Bar(); Foo y = new MyClass(); Foo sum = Foo.Add(x, y);一样使用。
标签: c# generics operator-overloading