다음과 같이 제네릭 타입을 가지고 있습니다.닫힌 제네릭 형식을 모른 채 일반 속성에 액세스하는 방법
public class TestGeneric<T>
{
public T Data { get; set; }
public TestGeneric(T data)
{
this.Data = data;
}
}
만약 내가 어떤 타입의 객체인지 알고있는 객체를 가지고 있다면, TestGeneric <> TypeParameter T를 알았습니다. 이제 객체의 데이터에 액세스해야합니다. 문제는 내가 어떤 TestGeneric을 닫았는지 정확하게 알지 못하기 때문에 객체를 캐스팅 할 수 없다는 것입니다.
// thx to http://stackoverflow.com/questions/457676/c-reflection-check-if-a-class-is-derived-from-a-generic-class
private static bool IsSubclassOfRawGeneric(Type rawGeneric, Type subclass)
{
while (subclass != typeof(object))
{
var cur = subclass.IsGenericType ? subclass.GetGenericTypeDefinition() : subclass;
if (rawGeneric == cur)
{
return true;
}
subclass = subclass.BaseType;
}
return false;
}
를 사용하여 제 객체가 제네릭 유형임을 확인합니다. 문제의 코드는 다음과 같습니다.
public static void Main()
{
object myObject = new TestGeneric<string>("test"); // or from another source
if (IsSubclassOfRawGeneric(typeof(TestGeneric<>), myObject.GetType()))
{
// the following gives an InvalidCastException
// var data = ((TestGeneric<object>)myObject).Data;
// if i try to access the property with reflection
// i get an InvalidOperationException
var dataProperty = typeof(TestGeneric<>).GetProperty("Data");
object data = dataProperty.GetValue(myObject, new object[] { });
}
}
형식에 관계없이 데이터가 필요합니다. 음, GetType()을 사용하여 형식을 요청할 수 있으면 좋지만 필요하지는 않습니다.) ToString()을 사용하여 xml로 덤프하십시오.
어떤 제안이 있습니까? 고맙습니다.
가능한 중복 (http://stackoverflow.com/questions/3059420/accessing-properties-through- : 그것은 더 많은 읽을 수있는 코드를 만드는 완벽한 사용 예제 generic-type-parameter) –