所以,我想做类似的事情:
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;
}
我不喜欢向基类进行反向转换,也不喜欢派生类...
答案 0 :(得分:4)
只需简单地调用+
运算符即可获得两个参数。其中一个类型为A
(左侧应始终为类型,即重载运算符的容器)
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
答案 1 :(得分: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();
}
}