[英]How to invoke Property/Field of Generic Type with Reflection
Consider Following class 考虑下课
class A<T> where T:new()
{
public static T Instance = new T();
A()
{
}
}
I have 2 questions 我有两个问题
I need Instance
object with Reflection. 我需要带有反射的
Instance
对象。 I have tried following 我尝试了以下
var type = typeof(A<int>); // var type = typeof(A<>).MakeGenericType(typeof(int)); // Also tried this var instanceMember1 = type.GetMember("Instance", BindingFlags.Static ); // returns null var instanceMember2 = type.GetField("Instance", BindingFlags.Static ); // returns null
I have also tried to Change Instance
to property and call GetProperty
with no success. 我也尝试将
Instance
更改为属性,并调用GetProperty
失败。
After removing new()
constraint and making constructor
private, How to invoke private (parameterless) constructor through reflection. 除去
new()
约束并将constructor
设为私有之后,如何通过反射调用私有(无参数)构造函数。
Add BindingFlags.Public
to your flags for GetField
. 将
BindingFlags.Public
添加到GetField
的标志中。
var instanceMember1 = type.GetField("Instance", BindingFlags.Static |
BindingFlags.Public);
To invoke the private constructor: 调用私有构造函数:
var ctor = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic,
null, Type.EmptyTypes, new ParameterModifier[0]);
var instance = ctor.Invoke(null) as A<int>;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.