Tilak
Tilak

Reputation: 30698

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

  2. After removing new() constraint and making constructor private, How to invoke private (parameterless) constructor through reflection.

Upvotes: 1

Views: 1108

Answers (1)

e_ne
e_ne

Reputation: 8459

Add BindingFlags.Public to your flags for 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>;

Upvotes: 1

Related Questions