在抽象基础

时间:2016-11-18 14:09:37

标签: c# inheritance

为糟糕的标题道歉,我想不出更好的方式来表达它。

基本上我有一个抽象基类Category和从中继承的整个派生类。是否可以按照以下方式做点什么:

List<Category> catList = new List<Category>();
catList.Add(new Category(myCategoryTypeString));

其中myCategoryTypeString将始终是其中一个派生类的名称,并让它创建该派生类的新对象(可能是使用字符串上的开关来确定要使用的类)。

这就是:

catList.Add(new Category("Engineering"));

会在列表中添加Engineering : Category类型的新对象吗?

如果可能的话怎么会这样做呢?我的抽象类是这样定义的:

abstract class Category
{
    private string line;
    private bool ToChallenge;
    private string[] columns;
    private int oppLevel;

    protected Category(string line)
    {
        this.line = line;
        columns = line.Split(',');
    }

    public abstract bool IsAnomoly();
    public abstract void CategoriseAnomoly();
    public abstract void WriteLine();

}

1 个答案:

答案 0 :(得分:5)

不,你不能这样做 - 如果你打电话给new Foo(),那将始终创建Foo的实例,而不是子类的实例。

而是在Category中创建一个静态工厂方法:

public static Category CreateCategory(string line)
{
    if (line == "Engineering")
    {
        return new EngineeringCategory();
    }
    // Whatever you want to do for non-engineering categories
}

正如评论中所述,使用实际类型名称可能并不是一个好主意,除非这已经是机器生成的输出。如果你真的想,你可以使用类似的东西:

public static Category CreateCategory(string typeName)
{
    // Note that the type name would have to be namespace-qualified here
    Type type = Type.GetType(typeName);
    return (Category) Activator.CreateInstance(type);
}