2015-09-04 64 views
0

比方說,我有一個「建築成本」計算類,它帶有一個子計算器列表。使用C#中繼承相同屬性的接口的方法

子計算器都定義了一個接口,該接口定義該子計算器所需的輸入。例如。 IWallsCostInputs,IRoofCostInputs。這使得子計算器能夠清楚地表達他們需要的數據。

有一個業務對象包含所有子計算器和更多的數據(如DateLastModified等)。例如。 BuildingCostInputs

我想BuildingCostCalculator採取定義所有需要

public interface IBuildingCostInputs : IWallsCostInputs, IRoofCostInputs 

但是如果在IWallsCostInputsIRoofCostInputs的重複屬性,這並不工作輸入接口。

我覺得我的選擇是如下:

  1. 使用new關鍵字在IBuildingCostInputs
  2. 定義一個實現IWallsCostInputsIRoofCostInputs一個抽象類,有BuildingCostInputs從中獲得並把它傳遞到BuildingCostCalculator
  3. 創建實現IWallsCostInputsIRoofCostInputs的POCO,在此和BuildingCostInputs之間的(自動)映射並將其傳遞到BuildingCostCalculator

(1)我覺得我willcause麻煩時,我通過IWallsCostInputsIRoofCostInputs引用複製的特性,並採用測試雙打(如MOQ)時。

(2)在特定情況下不起作用,因爲我的業務對象已經是繼承鏈的一部分。

(3)確實有效,它看起來像我需要做的。不過,我寧願避免映射和POCO的框架開銷。

有沒有人有任何意見,或有更好的方式來實現我想要做的?感覺就像我應該能夠以一種清晰,簡潔和富有表現力的方式來實現這一點,但也許這是不可能的。

謝謝

+1

Eh,*顯式接口實現*? https://msdn.microsoft.com/en-us/library/aa288461(v=vs.71).aspx –

+0

我不是顯式接口實現的粉絲,在這種情況下,我不明白它會如何比任何其他選擇都要好。 – cedd

+0

不熟悉c#或者這個試圖解決什麼問題,但是這對我來說看起來很奇怪,爲什麼你會有一個接口(基本上)定義數據結構而不是指定行爲? – blank

回答

1

如果你需要的屬性是一樣的,你可以繼承你的接口來自同一界面。

interface IConstructionInputs 
    { 
     DateTime DateLastModified { get; } 
    } 

    interface IRoofCostInputs : IConstructionInputs 
    { 
    } 

    interface IWallCostInputs : IConstructionInputs 
    { 
    } 

    interface IBuildingCostInputs : IRoofCostInputs, IWallCostInputs 
    { 
    } 

    class BuildingCostInputs : IBuildingCostInputs 
    { 
     public DateTime DateLastModified { get; private set; } 
    } 
+0

喜歡它。這對我來說可能有點困難,因爲我有很多具有各種重複屬性的子計算器,並且沒有任何明顯的分類潛力,但是這將工作並且比我的任何原始選項都要好。我仍然認爲應該有可能做更好的事情,但很可能事實上並非如此。 – cedd

1

我會重新思考我是否需要繼承。如果你有一個共同的接口,你可以這樣做:

public interface IBuildingCostInput 
{ 
    IReadOnlyCollection<ICostInputs> CostInputs {get;} 
} 

,或者如果你想成爲明確的,也許是:

public interface IBuildingCostInput 
{ 
    IWallsCostInputs WallCostInputs {get;} 
    IRoofCostInputs RoofCostInputs {get;} 
} 
+0

嗨。我想將一個對象傳遞給BuildingCostCalculator,然後將這個對象傳遞給所有的子計算器。你的第二種方法可以工作(所以非常感謝!),但代價是使BuildingCostCalculator更復雜一些,並且實現了IBuildingCostInput的額外框架。我不知道這個額外的faff與我目前的選項3相比如何。 – cedd