2017-01-25 1 views
0

좋아, 이상하게 들릴지 모르지만, object이 나에게 전달 된 것이 인 경우, 나는 T이 실제로 무엇인지 신경 쓰지 않아도되는지 테스트해야합니다. 즉, ModelItem<int>, ModelItem<string> 또는 ModelItem<Foo> 인 경우 true을 반환해야합니다.제네릭의베이스를 테스트 할 수 있습니까?

참고 : 내가 ModelItem<T>의 소유자 인 경우 IModelItem 유형의 인터페이스를 정의한 다음 ModelItem<T> 정의의 일부로 할당한다고 생각하지만 원본에 액세스 할 수는 없습니다.

답변

2

는 물론, 그것은 가능 :

public bool IsIt(object thing) 
{ 
    var type = thing.GetType(); 
    if (type.IsGenericType) 
    { 
     return type.GetGenericTypeDefinition() == typeof(MyThing<>); 
    } 
    return false; 
} 

시험이 :

IsIt(new MyThing<int>()).Dump(); 
IsIt(new MyThing<string>()).Dump(); 
IsIt(new MyThing<Foo>()).Dump(); 
IsIt(5).Dump(); 

반환

True 
True 
True 
False