【发布时间】:2012-07-11 23:02:45
【问题描述】:
问题是我们不能获取仅位于具有泛型类型的基类中的字段(非泛型)的值。 请参阅下面的代码 sn-p。打电话
f.GetValue(a)
将抛出异常并显示消息:不能对 Type.ContainsGenericParameters 为 true 的类型的字段执行后期绑定操作。
class Program
{
static void Main(string[] args)
{
Type abstractGenericType = typeof (ClassB<>);
FieldInfo[] fieldInfos =
abstractGenericType.GetFields(BindingFlags.Public | BindingFlags.Instance);
ClassA a = new ClassA("hello");
foreach(FieldInfo f in fieldInfos)
{
f.GetValue(a);// throws InvalidOperationhException
}
}
}
internal class ClassB<T>
{
public string str;
public ClassB(string s)
{
str = s;
}
}
internal class ClassA : ClassB<String>
{
public ClassA(string value) : base(value)
{}
}
我们的设计要求我们在获得任何实际对象的实例之前首先获得 FieldInfo。所以我们不能使用
Type typeA = abstractGenericType.MakeGenericType(typeof(string));
FieldInfo[] fieldInfos = typeA.GetFields();
谢谢
【问题讨论】:
-
发布的问题没有多大意义。您将必须使用对象实例来调用GetValue()。所以只需使用
a.GetType()来获取具体的泛型类型,没有必要通过不完整的类型。
标签: c# generics reflection fieldinfo