c# - 这是实现使用算术的多态性的好方法吗?
问题描述
所以我想使用多态性来使用算术。
因此,我的第一个想法是创建一个使用算术、IAddable 等的接口;但是我在互联网上发现这是不可能的。但是我想到了一个窍门,现在我想知道:这是多态性的一个很好且快速的实现吗?
public abstract class RingElement
{
public static RingElement operator +(RingElement e1, RingElement e2)
{
if (e1 == null)
return e2;
if (e2 == null)
return e1;
Type type = e1.GetType();
return (RingElement) type.GetMethod("op_Addition").Invoke(null, new object[] {e1, e2 });
}
public static RingElement operator *(RingElement e1, RingElement e2)
{
if (e1 == null)
return e2;
if (e2 == null)
return e1;
Type type = e1.GetType();
return (RingElement) type.GetMethod("op_Multiply").Invoke(null, new object[] { e1, e2 });
}
}
我制作了两个 RingElement:一个 doubleElement(只包含一个 double)和一个泛型
Matrix<T> : RingElement where T : RingElement
null 处理是为了实现空总和或空乘积的可能性。
每个继承的 RingElement 类都应该有两个静态方法
public static T operator +(T x, T y)
public static T operator *(T x, T y)
具有自己的实现主体,其中 T 是类类型
解决方案
你有点太早了))。(链接)中有Type Classes
可能是最优雅的解决方案。c# 9
c#
(如果 usingf#
是一个选项,它已经具有Statically Resolved Type Parameters,并且此链接下的页面准确显示了算术多态性的示例)
推荐阅读
- highcharts - 我可以使用 highchart 构建圆形热图吗
- google-cloud-platform - 谷歌云 SDK 安装错误:无法更新 [/Users/username/.bash_profile]。确保您对此位置具有写入权限
- javascript - npm 不断在全球范围内安装
- python - [0,0] 表达式有什么作用?
- python - 循环列以一次比较数据框中的两列,并根据每个比较结果添加一个汇总列
- ios - 构建失败并显示“命令 PrecompileSwiftBridgingHeader 失败,退出代码为非零”
- laravel - 如何在 Laravel 中使非数据库模型具有两个属性
- android - 使用 react-native init 后如何在 expo 上运行 React-Native 应用程序?
- google-apis-explorer - 如何通过 Youtube Data API 获取 Youtube 频道页面上的“关于”部分详细信息?
- ios - 在 Apple Watch 模拟器中打开网页