使用typeof时类型的继承

本文关键字:继承 类型 typeof 使用 | 更新日期: 2023-09-27 17:49:44

我想创建一个这样的类结构:

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#库

使用typeof时类型的继承

我确实认为你在寻找泛型,但我不完全确定,因为你的问题不清楚…

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)
    {
    }
}