将继承基类的类设置为集合中的工作类型


MasterClass

基类,Attachvariable继承自基类。 Table存储大师类对象。

public class Table
{
    private Dictionary<int, MasterClass> map = new Dictionary<int, MasterClass>();
    public bool isInMemory(int id)
    {
        if (map.ContainsKey(id))
            return true;
        return false;
    }
    public void doStuffAndAdd(MasterClass theclass)
    {
        theclass.setSomething("lalala");
        theclass.doSomething();
        map[theclass.id] = theclass;
    }
    public MasterClass getIt(int id)
    {
        return map[id];
    }
}

所以现在发生这种情况:

Table table = new Table();
if (!table.isInMemory(22))
{
    Attachvariable attachtest = new Attachvariable(22);
    table.doStuffAndAdd(attachtest);
    Console.WriteLine(attachtest.get_position()); //Get_position is a function in Attachvariable 
}
else
{
    Attachvariable attachtest = table.getIt(22); //Error: Can't convert MasterClass to Attachvariable
    Console.WriteLine(attachtest.get_position());
}

有没有办法让Table使用从MasterClass继承的任何类,而无需预先知道该类的存在,以便我仍然可以使用 doStuffAndAdd(MasterClass theclass) 并使用 Attachvariable 作为getIt()的返回类型。

我不能使用Table<T>因为doStuffAndAdd无法将MasterClass对象添加到字典中。没有办法检查 T 是否继承自大师班,所以这并不奇怪......我该如何完成这项工作?

public class Table<T>
{
    private Dictionary<int, T> map = new Dictionary<int, T>();
    public bool isInMemory(int id)
    {
        if (map.ContainsKey(id))
            return true;
        return false;
    }
    public void doStuffAndAdd(MasterClass theclass)
    {
        theclass.setSomething("lalala");
        theclass.doSomething();
        map[theclass.id] = theclass; //Error: can't convert MasterClass to T
    }
    public T getIt(int id)
    {
        return map[id];
    }
}

我相信这一点:

public void doStuffAndAdd(MasterClass theclass)
    {
        theclass.setSomething("lalala");
        theclass.doSomething();
        map[theclass.id] = theclass; //Error: can't convert MasterClass to T
    }

必须是

public void doStuffAndAdd(T theclass)
    {
        theclass.setSomething("lalala");
        theclass.doSomething();
        map[theclass.id] = theclass; //should work 
    }

您可以通过执行以下操作来检查一个类是否继承了另一个类:

if(theclass is MasterClass)
{}

最新更新