2012-10-02 2 views
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()); 
} 

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

을 Attachvariable attachtest = 새 MasterClass (22); ' 대신에? – MyCodeSucks

+0

@KevinH. 컴파일하지 않을 것입니다. –

답변

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

그 문제는 T가 없기 때문에 MasterClass.setSomething() 함수 등을 사용할 수 없다는 것입니다. – natli

+3

클래스 선언에서'T'에 대한 제약 조건을 넣어야합니다 :'public class Table T : MasterClass' –

+0

이 함수를 얻기 위해 T에 제약 조건을 추가하십시오 @natli –

관련 문제