本文介绍了有没有在C#中的任何方式来执行操作符重载在派生类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要定义具有执行某些运算符重载它实现它的各类接口。似乎没有一个明显的方式做到这一点,因为操作符重载已经用在类的静态方法来完成。有什么办法来达到同样的效果(使用抽象类或其他任何东西)?

I need to define an Interface which has to enforce certain operator overloading to the types which implements it. There doesn't seem an obvious way to do it since operator overloading has to be done using static methods in class. Is there any way to achieve the same effect (using abstract classes or anything else)?

推荐答案

一个黑客,而是位。 ..

Bit of a hack, but...

您可以提供你的基类运算符重载然后调用一些出版抽象方法的类中的一个做的工作有。

You could provide operator overloads in your base class that then call some published abstract methods in one of the classes to do the job there.

public abstract class MyClass
{
    public static MyClass operator +(MyClass c1, MyClass c2) 
    {
        return c1.__DoAddition(c2);
    }

    protected abstract MyClass __DoAddition(MyClass c2);
}

这篇关于有没有在C#中的任何方式来执行操作符重载在派生类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 09:43