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