2016-12-14 120 views
0

我有一个父类和另一个继承父类的子类。覆盖操作符重载方法

我有一个操作符在父内重载方法,我想使它也可以在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); 
    } 
} 

有一个更好的方法来实现这一点?非常感谢你。

+0

你尝试使用母公司的类型发起一个子类对象,如“父=新的Child ();” –

+0

即使我使用Parent启动,我如何将(Parent + Parent)转换回Child? – user3545752

+0

备注:当你面对这个问题时,可能意味着没有人能够理解家长和孩子期待什么,因此将无法阅读代码。在这一点上建设者的方法或不同的东西可能是更好的选择。 –

回答

1

最终,您必须创建Child对象,但可以将该逻辑移动到受保护的方法中。

public class Parent 
{ 
    public int age; 
    public static Parent operator + (Parent a, Parent b) 
    { 
    Parent c = new Parent(); 
    AddImplementation(a, b, c); 
    return c; 
    } 

    protected static void AddImplementation(Parent a, Parent b, Parent sum) 
    { 
    sum.age = a.age + b.age; 
    } 
} 

public class Child : Parent 
{ 
    public static Child operator + (Child a, Child b) 
    { 
    Child c = new Child(); 
    AddImplementation(a, b, c); 
    return c; 
    } 
} 

或者另一种选择是将逻辑移动到保护构造,操作者调用

public class Parent 
{ 
    public int age; 
    public static Parent operator +(Parent a, Parent b) 
    { 
     return new Parent(a, b); 
    } 

    protected Parent(Parent a, Parent b) 
    { 
     this.age = a.age + b.age; 
    } 
} 

public class Child : Parent 
{ 
    public static Child operator +(Child a, Child b) 
    { 
     return new Child(a, b); 
    } 

    protected Child(Child a, Child b) : base(a,b) 
    { 
     // anything you need to do for adding children on top of the parent code. 
    } 
}