【发布时间】:2011-01-04 10:35:26
【问题描述】:
我有一个通用类型如下
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 中。
有什么建议吗?谢谢。
【问题讨论】:
标签: c# reflection casting generics