首页 > 解决方案 > 这是实现使用算术的多态性的好方法吗?

问题描述

所以我想使用多态性来使用算术。

因此,我的第一个想法是创建一个使用算术、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 是类类型

标签: c#abstract-class

解决方案


你有点太早了))。(链接)中有Type Classes可能是最优雅的解决方案。c# 9c#

(如果 usingf#是一个选项,它已经具有Statically Resolved Type Parameters,并且此链接下的页面准确显示了算术多态性的示例)


推荐阅读