2016-12-14 113 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. 
    } 
}