samedi 7 avril 2018

Use reflection to find a private field within `this` class, and instantiate it

Hypothetical situation. Say I had a class which contained numerous private fields. I want it to instantiate every field that it can find with the correct type. So far, I have used

public class TestClass
{
    private SomeClass sc;
    private AnotherClass ac;

    public TestClass()
    {
        var type = GetType();
        var fields = type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
            .Select(x => x.Name)
            .ToList();

        foreach (var f in fields)
            type.GetField(f).SetValue(/*instantiate here*/);
    }
}

How would one instantiate it?





Aucun commentaire:

Enregistrer un commentaire