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

4

1 回答 1

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 中将方法更改为虚拟方法,则可以在派生类中使用关键字“new”。

于 2011-12-19T23:35:12.993 回答