0

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

1 回答 1

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)
{}
于 2012-10-02T21:36:46.483 回答