2011-12-19 74 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虚拟的,那么你可以在派生类中使用关键字“新”。