简体   繁体   English

如何使用反射调用泛型类型的属性/字段

[英]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 我有两个问题

  1. 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失败。

  2. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM