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());
}
MasterClass
에서 상속하는 모든 클래스와 Table
작업을 할 수있는 방법은, 그 클래스 '정면의 실존에 대해 알지 못하고, 거기에 나는 아직도 할 수 있도록 을 사용하고 getIt()
의 반환 유형으로 Attachvariable
을 사용하십시오.
doStuffAndAdd가 사전에 MasterClass 개체를 추가 할 수 없기 때문에 Table<T>
을 사용할 수 없습니다. 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];
}
}
을 Attachvariable attachtest = 새 MasterClass (22); ' 대신에? – MyCodeSucks
@KevinH. 컴파일하지 않을 것입니다. –