2014-12-22 4 views
-2

나는이 손에서 다음 코드를하위 클래스에 대한 제네릭 형식으로 개체를 캐스팅하는 방법?

class Document {} 
class Track : Document {} 
class Album : Document {} 

class CellWrapper<T> {} 

class TableViewSource { 

    protected void CreateCellForItem(object item) { 
     // item is an instance of CellWrapper<T> where T is a document extending Document 
    } 
} 

CellWrapper<Document>item을 행사할 가능성이 있습니까?

내가 알고있는 것처럼, 내가 그런 식으로 뭔가를 필요로하는 방법에 대해 뭔가를 정의 할 수는 있지만,이 경우에는 작동하는 것을 찾을 수 없었다.

그냥 그것을 명확히

CellWrapper<Document> wrapper = item as CellWrapper<T> where T : Document; 

편집 : 나는이 같은

뭔가가 컴파일되지 않습니다 (캐스트되지 않음)가 CellWrapper의 인스턴스의 확인에만 수 있어요이 질문이 Casting generic typed object to subtype과 다른 경우 itemIList과 같이 열거 가능한 객체 인 경우 이름이 지정된 솔루션 만 해결할 수 있습니다. 내 예에서는 맞춤 클래스입니다. 여기에 제공된 솔루션은 여기에서 내 문제에는 적용되지 않습니다.

+1

왜 '객체'유형을 사용 하시겠습니까? –

+0

@YuvalItzchakov, 그건 인터페이스의 일부입니다 ... 나는 그것을 바꿀 수 없습니다. – SimonSimCity

+0

여기 반영하지 않고 해결할 수있는 경우 도움이 될 것입니다. http://igoro.com/archive/fun-with-c-generics-down-casting-to-a-generic-type/ – SimonSimCity

답변

2

, 당신은 반사를 사용하여 속성에 액세스 할 수 있습니다. 그러나이 값은 CellWrapper<Document>으로 변환되지 않습니다.

class Document { 
    public string Key { get; set; } 
} 
class Track : Document {} 
class Album : Document { } 

class CellWrapper<T> where T : Document { 
    public T Document { get; set; } 
} 

class TableViewSource 
{ 

    public void CreateCellForItem(object item) 
    { 
     var documentProperty = item.GetType().GetProperty("Document"); 
     var document = (Document)documentProperty.GetValue(item); 
     Console.WriteLine(document.Key); 
    } 
} 
-1

그냥이 : 당신은 T 타입의 속성에 액세스해야하는 경우

CellWrapper<Document> wrapper = item as CellWrapper<Document>; 
+0

당신은'CellWrapper '또는'CellWrapper '의 인스턴스를 가지고 있습니다 ... – SimonSimCity

관련 문제