C#不允许将操作符重载方法定义为泛型方法(转载)
在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 } }
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?
答
No, you can't declare generic operators in C#.
Operators and inheritance don't really mix well.
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+;
一个变通的方法是,我们可以将泛型参数T声明在类Foo上,而不是在操作符重载方法上:
class Foo<T> { public static Foo<T> operator +(Foo<T> a, T b) { return a; } }
可以参考:Arithmetic operator overloading for a generic class in C#
原文链接:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
2019-08-14 C#使用HttpWebRequest发送数据和使用HttpWebResponse接收数据的一个简单示例
2015-08-14 用javascript在客户端删除某一个cookie键值对