2011-12-19 60 views
0

我有了一個類,如下C#組件:委託 - 最佳實踐

namespace SharedComponent{ 
     class TestResult { 
      //several members 
     } 
    } 

在我引用這個組件另一個現有的C#應用​​程序,我需要實例化這個同一類,但與附加標識符如下。

namespace ClientApplication { 
     class TestResult 
     { 
      //exact same members as above including methods 
      //actually the shared component class was created by gleaming 
      //that from this application! 
      int PersonID; //additional identifier 
        //not suitable to have in the shared component 
     } 
    } 

在客戶端應用程序中有幾種依賴附加標識符的方法。所以對我來說,仿效一個拷貝構造函數並創建這個對象並填充附加參數是非常誘人的。這樣我就可以使用現有的功能,只需對類進行最少的更改。

另一種方法可以是將其餘細節添加爲客戶端實現的引用。

namespace ClientApplication { 
    class TestResult { 
     SharedComponent.TestResult trshared = new SharedComponent.TestResult() 
     //but this warrants I have my class methods to delegate 
     //to the sharedcomponent throughout ; example below 

     internal bool IsFollowUp(ClientApplication.TestResult prevTest) 
     { 
     //a similar method is being used 
       //where a function takes the class object as parameter 
       trshared.IsFollowUp(prevTest.trshared); 
     } 

     int PersonID; //additional identifier 

    } 
} 

哪個選項更好?這方面的最佳做法是什麼?

環境:VS2008,C#,WINXP/Win7的

+0

客戶端應用程序類是否可以從原始繼承? – sq33G 2011-12-19 23:30:15

回答

2

這聽起來好像你ClientApplication.TestResult 「是」 SharedComponent.TestResult。假設SharedComponent.TestResult未被封裝,您可以從該類繼承。這樣你就不必複製粘貼代碼。如果您還能夠修改SharedComponent.TestResult,那麼您可以將方法聲明爲虛擬的,並在ClientApplication.TestResult中覆蓋它們的行爲。

class TestResult : SharedComponent.TestResult 
{ 
    int PersonId { get; set; } 

    override bool IsFollowUp(ClientApplication.TestResult prevTest) 
    { 
      // Your own implementation or trivial (base.IsFollowUp(ClientApplication.TestResult.prevTest.trShared) 
    } 
} 

如果你不能改變的方法是在SharedComponent.TestResult虛擬的,那麼你可以在派生類中使用關鍵字「新」。