dimanche 10 mai 2015

How can I use reflection in C# to create an instance of a field?

I have the following classes:

// field within controller class I'd like to activate
public class View
{
    ...
}

// controller class
public static class Controller
{
    private static Model _model;
    public static Model {get{return _model;} set{_model = value;}}

    private static View _view;
    public static View {get{return _view;} set{_view = value;}}
}

I would like to instantiate the '_view' field using reflection. Here is what I have so far:

// get field info
System.Reflection.FieldInfo fieldInfo = typeof(Controller).GetField("_view", BindingFlags.NonPublic | BindingFlags.Static);

// cast FieldInfo to Type ... 
//   This is necessary for Activator.CreateInstance(Type t)
//   This cast does not succeed
Type t = (Type)fieldInfo;

I cannot use System.Reflection.FieldInfo.GetValue() because the instance will not have been instantiated.





Aucun commentaire:

Enregistrer un commentaire