从继承的类中获取特定方法

时间:2016-12-30 07:59:15

标签: c# inheritance base

我的对象模型下面有简单的继承:

public class RuntimeApiManagerBase
{
}

public class CatalogRuntimeApiManagerBase : RuntimeApiManagerBase
{
    public void Method1()
    {
    }
}

public class DocumentRuntimeApiManagerBase : RuntimeApiManagerBase
{
    public void Method2()
    {
    }

    public void Method3()
    {
    }
}

public class BaseObject
{
    public BaseObject(RuntimeApiManagerBase runtimeApiMgr)
    {
        RuntimeApiMgr = runtimeApiMgr;
    }
    public RuntimeApiManagerBase RuntimeApiMgr { get; set; }
}

public class Catalog : BaseObject
{
    public Catalog() : base(new CatalogRuntimeApiManagerBase())
    {
    }
}

public class Document : BaseObject
{
    public Document() : base(new DocumentRuntimeApiManagerBase())
    {
    }
}

现在,我想基于完全派生的类型访问RuntimeApiMgr属性的方法。但是,它没有显示任何符合逻辑的内容:

Catalog c1 = new Catalog();

// c1.RuntimeApiMgr. => No Method1

Document d1 = new Document();
// d1.RuntimeApiMgr. => No Method2 and Method3

是否可以使用不同的结构,如泛型或其他东西?

感谢您的时间。

3 个答案:

答案 0 :(得分:4)

您可以使用RuntimeApiManagerBase作为泛型,并且具有类型约束,其中T必须是RuntimeApiManagerBase的子类

    public class BaseObject<T> where T : RuntimeApiManagerBase
    {
        public BaseObject(T runtimeApiMgr)
        {
            RuntimeApiMgr = runtimeApiMgr;
        }
        public T RuntimeApiMgr { get; set; }
    }

    public class Catalog : BaseObject<CatalogRuntimeApiManagerBase>
    {
        public Catalog() : base(new CatalogRuntimeApiManagerBase())
        {
        }
    }

    public class Document : BaseObject<DocumentRuntimeApiManagerBase>
    {
        public Document() : base(new DocumentRuntimeApiManagerBase())
        {
        }
    }

    Catalog c1 = new Catalog();

    c1.RuntimeApiMgr.Method1();

    Document d1 = new Document();
    d1.RuntimeApiMgr.Method2();

答案 1 :(得分:4)

使用泛型:

public class BaseObject<T>
  where T : RuntimeApiManagerBase
{
    public BaseObject(T runtimeApiMgr)
    {
        RuntimeApiMgr = runtimeApiMgr;
    }
    public T RuntimeApiMgr { get; set; }
}

public class Catalog : BaseObject<CatalogRuntimeApiManagerBase>
{
    public Catalog() : base(new CatalogRuntimeApiManagerBase())
    {
    }
}

public class Document : BaseObject<DocumentRuntimeApiManagerBase>
{
    public Document() : base(new DocumentRuntimeApiManagerBase())
    {
    }
}

在这种情况下,您的c1.RuntimeApiMgr属于CatalogRuntimeApiManagerBase类型,并且会Method1

答案 2 :(得分:1)

使用泛型的解决方案的替代方案是一种老式的铸造方法。 也许是这样的:

Catalog c1 = new Catalog();
(c1.RuntimeApiMgr as CatalogRuntimeApiManagerBase).Method1();


Document d1 = new Document();
(d1.RuntimeApiMgr as DocumentRuntimeApiManagerBase).Method2();

或者在Caltalog和Document classes中创建具有相同名称的新属性:

public class Catalog : BaseObject
{
  public Catalog() : base(new CatalogRuntimeApiManagerBase())
  {
  }

  public new CatalogRuntimeApiManagerBase RuntimeApiMgr { get; set; }
}