C# 泛型运算符 [英] C# Generic Operators

查看:38
本文介绍了C# 泛型运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一个像这样的通用运算符:

I am trying to implement a generic operator like so:

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.我希望使用通用运算符 + 来解决这个问题,但我只是收到了上述内容的语法错误(在 < 处),这让我相信这样的代码是不合法的.

Really what I'm trying to do is gracefully handle inheritance. With a standard operator + in Foo, where T is instead "Foo", if anyone is derived from Foo (say Bar inherits Foo), then a Bar + Bar operation will still return a Foo. I was hoping to solve this with a generic operator +, but I just get a syntax error for the above (at the <) making me believe that such code is not legal.

有没有办法制作泛型运算符?

Is there a way to make a generic operator?

推荐答案

不,您不能在 C# 中声明泛型运算符.

No, you can't declare generic operators in C#.

运算符和继承并不能很好地混合.

Operators and inheritance don't really mix well.

如果你想让 Foo + Foo 返回一个 Foo 而 Bar + Bar 返回一个 Bar,你需要在每个类上定义一个运算符.但是,由于运算符是静态的,您将无法获得多态的好处,因为调用哪个运算符将在编译时决定:

If you want Foo + Foo to return a Foo and Bar + Bar to return a Bar, you will need to define one operator on each class. But, since operators are static, you won't get the benefits of polymorphism because which operator to call will be decided at compile-time:

Foo x = new Bar();
Foo y = new Bar();
var z = x + y; // calls Foo.operator+;

这篇关于C# 泛型运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆