C#Parent Class,具有基于接口的属性,可以根据子类声明进行更改

时间:2011-03-21 14:48:26

标签: c# interface properties subclassing

我环顾四周但却无法理解我正在尝试做的事情。我想创建一个基线接口,可以从中派生出多个其他类。没问题。然后,我想要另一个在公共接口基础上具有属性的类,但不保证它将使用哪个子类的接口版本。我应该使用什么方法。这是我正在尝试模拟的一些例子。

public interface IBaseline
{
    string CommonToAll { get; }
    int AnotherCommon { get; }

    void CommonFunction();
}

现在,从IBaseline接口

派生新类
public class CDerived1 : IBaseline
{
    private string CommonToAll
    { get { return Whatever; }}

    private int AnotherCommon
    { get { reutrn WhateverInt; }}

    public void CommonFunction)
    { // do something with this classes specific elements...  }


    // now, here are some custom things specific to this class
    private string CustomToThisClass;

    private int CustomFunction()
    { // do something }
}

public class CDerived2: IBaseline
{
    private string CommonToAll
    { get { return Whatever; }}

    private int AnotherCommon
    { get { reutrn WhateverInt; }}

    public void CommonFunction)
    { // do something with this classes specific elements...  }

    // again, these are totally different to the second derived class
    private string TotallyDifferent;

    private bool DiffFunction( int anyParm )
    {  // do something different }

}

现在,我的困惑实施了。我想创建一个新的类,其上有一个可以是任何IBaseline结构的字段,但在编译时不知道哪个版本。

public class OtherClass
{
   IBaseline GenericInstance;
   ...
   ...

   public void CommonAccessFunction()
   {
      // call the common function that is generic no matter WHAT 
      // subclassed instance is used.
      GenericInstance.CommonFunction();
   }
}

2 个答案:

答案 0 :(得分:2)

使其成为通用:

public class OtherClass<T> where T : IBaseline
{
    public T GenericInstance { get; private set;}

    public OtherClass(T genericInstance)
    {
        this.GenericInstance = genericInstance;
    }
}

答案 1 :(得分:1)

为什么不能通过构造函数(如下例所示)或通过属性将IBaseLine的实例传递给OtherClass?

public class OtherClass
{
   IBaseline GenericInstance;

   public OtherClass(IBaseline instance)
   {
        GenericInstance=instance;
   }

   public void CommonAccessFunction()
   {
      // call the common function that is generic no matter WHAT 
      // subclassed instance is used.
      GenericInstance.CommonFunction();
   }
}
或者我错过了什么或者你的问题不是很清楚。看来你想要做的就是标准练习,你对OtherClass的实现并不知道它正在使用哪个IBaseline实现,只是它正在使用一些实现......