C# 中是否有任何方法可以在派生类中强制执行运算符重载? [英] Is there any way in C# to enforce operator overloading in derived classes?

查看:17
本文介绍了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# 中是否有任何方法可以在派生类中强制执行运算符重载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆