【发布时间】:2016-12-14 02:38:54
【问题描述】:
我有一个父类和另一个继承父类的子类。
我在 Parent 中有一个运算符重载方法,我想让它也适用于 Child。但是我不确定如何执行此操作。
public class Parent
{
public int age;
public static Parent operator + (Parent a, Parent b)
{
Parent c = new Parent();
c.age = a.age + b.age;
return c;
}
}
public class Child : Parent
{
//other fields...
}
我能想到的唯一方法是将完全相同的方法和逻辑复制给孩子。但是我认为这不是一个好方法,因为代码是多余的:(尤其是当代码很长时)
public class Child : Parent
{
public static Child operator + (Child a, Child b)
{
Child c = new Child();
c.age = a.age + b.age;
return c;
}
}
我尝试进行强制转换,但在运行时失败:
public class Child : Parent
{
public static Child operator + (Child a, Child b)
{
return (Child)((Parent)a + (Parent)b);
}
}
有没有更好的方法来实现这一点?非常感谢。
【问题讨论】:
-
你是否尝试过使用父类的类型来启动一个子类对象比如“Parent A = new Child();”
-
即使我使用Parent发起,如何将(Parent + Parent)转换回Child?
-
旁注:当您遇到此问题时,这可能意味着没有人能够理解 Parent + Child 的期望,因此将无法阅读代码。此时,使用构建器方法或其他方法可能是更好的选择。
标签: c# class operator-overloading overriding