使用typeof时类型的继承

时间:2014-03-12 23:19:23

标签: c# generics inheritance abstraction typeof

我试图创建这样的类结构:

public abstract class ParentClass
{
    protected virtual void BuildQueries()
    {
        var Engine = new FileHelperEngine(typeof(TopType));
        DataPoints = Engine.ReadFile(ResumeName) as TopType[];
    }

    protected Parent TopType;
}

public class ChildClass : ParentClass
{
   protected override Child TopType
}

和类型:

public abstract class Parent
{
   //some class members here
}

public class Child : Parent
{
   //some class members here
}

我认为这里有一个简单的答案,但我对C#来说太新了,无法弄清楚我应该用什么谷歌搜索。我尝试过使用泛型,但我无法做到正确。

我知道没有继承我就会写

var Engine = new FileHelperEngine(typeof(Parent));

但这是我努力想象的继承的一部分。

很抱歉,我没有提到FileHelperEngine引用了FileHelpers C#库

1 个答案:

答案 0 :(得分:3)

我认为你在寻找仿制药,但我不完全确定,因为你的问题不明确......

public abstract class ParentClass<T> where T : Parent
{
    protected virtual void BuildQueries()
    {
        var Engine = new FileHelperEngine<T>();
        var r = Engine.ReadFile(ResumeName);
    }

    protected T TopType { get; set; }

    // (...)
}

public class ChildClass : ParentClass<Child>
{
    // don't need to override anything, because your property is generic now
    // which means it will be of type `Child` for this class
}

public class FileHelperEngine<T>
    where T : Parent  // this generic constraint might not be necessary
{
    public T[] ReadFile(string name)
    {
    }
}