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

时间:2012-10-02 21:32:06

标签: c# inheritance polymorphism

MasterClass是基类,Attachvariable继承自此类。 Table存储MasterClass对象。

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对象添加到Dictionary中。没有办法检查T是否继承了MasterClass,这并不令人惊讶......我该如何使用呢?

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];
    }
}

1 个答案:

答案 0 :(得分:1)

我相信:

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