Reputation: 30698
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. 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.
After removing new()
constraint and making constructor
private, How to invoke private (parameterless) constructor through reflection.
Upvotes: 1
Views: 1108
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