C#泛型运营商 [英] C# Generic Operators

查看:124
本文介绍了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
   }
}

真的是我想要做的是优雅地处理继承。随着标准操作员在+美孚,其中T是不是富,如果有人从美孚派生(比如酒吧继承美孚),那么一个酒吧+酒吧的操作仍然会返回一个Foo。我希望有一个通用的运营商+来解决这个问题,但我只是得到一个语法错误对于上述(在在&lt;)使我相信,这样code是不合法的。

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和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天全站免登陆