0

所以,我想做类似的事情:

 Class A
{
    public static A operator + (A left, A right)
    {
        //Calculations
        return new A();
    }
}

Class B : A
{
    public static B operator + (B left, B right)
    {
        //Calculations
        base.+(left,right);
        return new A();
    }
}

编辑

编辑:

如果不对基类进行类型转换就可以实现这一点,因为它变得丑陋:

public static Sums operator -(Sums operand1, Sums operand2)
{
   Sums res = new Sums(operand1._parent);
   res = (Sums) (operand1 - (srp_AccountPension.PensionSums)operand2);
   return res;

 }

我不喜欢来回转换到基类并再次转换到派生类......

4

2 回答 2

4

只需简单地+为两个参数调用运算符。has 类型A之一(左边的应该总是 of 类型,即重载运算符的容器)

public class A
{
    public static A operator + (A left, A right)
    {
        //Calculations
        Console.WriteLine ("base A was called");
        return new A();
    }
}

public class B : A
{
    public static B operator + (B left, B right)
    {
        //Calculations
        A res = right + (A)left;
        return new B();
    }
}

现在打电话

var B = new B() + new B();

将打印:

base A was called
于 2013-11-13T05:17:01.923 回答
3

重新定义这样的静态方法看起来并不好。我的建议是使用模板方法设计模式,这使得 + 运算符成为模板方法,

class A
{
    public virtual A Plus(A right)
    {
        return new A();
    }

    public static A operator + (A left, A right)
    {
        //Calculations and handle left == null case.
        return left.Plus(right);
    }
}

class B : A
{
    public override B Plus(B right)
    {
        //Calculations
        base.Plus(right);
        return new A();
    }
}
于 2013-11-13T05:43:59.520 回答