[英]InvokeMember on generic class results in an exception
I have the following classes 我有以下课程
public class RowDef
{
string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
public RowDef()
{
}
public RowDef(string name)
: this()
{
Name = name;
}
}
public class RowDef<T> : RowDef
{
public RowDef()
{
}
public RowDef(string name)
: base(name)
{
}
T _value;
public T Value
{
get { return _value; }
set { _value = value;}
}
}
I am trying to use reflection to get the value of the "Value" property like this 我正在尝试使用反射来获取像这样的“ Value”属性的值
List<RowDef> rows = new List<RowDef>() { new RowDef<int>() { Value = 5 }, new RowDef<float>() { Value = 5.0f }, new RowDef<string>() { Value = "XXXX" } };
foreach (var row in rows)
{
var v = typeof(RowDef<>).InvokeMember("Value", BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.GetProperty, null, child, null);
}
But I get the following exception 但我得到以下异常
A first chance exception of type 'System.InvalidOperationException' occurred in mscorlib.dll Additional information: Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true. mscorlib.dll中发生了类型'System.InvalidOperationException'的第一次机会异常。其他信息:无法对包含ContainsGenericParameters为true的类型或方法执行后期绑定操作。
what can I do to fix the problem? 我该怎么解决该问题?
As the error is trying to tell you, it doesn't make sense to to use RowDef<>
directly. 由于该错误正试图告诉您,因此直接使用RowDef<>
没有任何意义。 RowDef<>
isn't really a type; RowDef<>
并不是真正的类型。 it's a type constructor that can be used to make concrete types like RowDef<string>
. 这是一个类型构造函数 ,可用于创建具体类型,如RowDef<string>
。
In your particular example, you actually just want row.GetType()
, which will return the concrete RowDef<T>
type of that instance. 在您的特定示例中,您实际上只想要row.GetType()
,它将返回该实例的具体RowDef<T>
类型。
Or, better yet, don't use Reflection at all, and instead add an abstract object UntypedValue
property to the base class and use that. 或者更好的是,根本不使用Reflection,而是将一个abstract object UntypedValue
属性添加到基类中并使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.