简体   繁体   English

使用反射在`this`类中查找私有字段,并将其实例化

[英]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 . 我希望它用正确的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? 一个如何实例化它? (this is assuming the new() constructor in each class is parameterless and is not empty) (这假设每个类中的new()构造函数都是无参数的并且不为空)

Activator.CreateInstance(Type) can create an instance from the type. Activator.CreateInstance(Type)可以从该类型创建实例。 This requires a parameter-less constructor (there are overloads for parameters). 这需要一个无参数的构造函数(参数有重载)。

To use it, just modify your code a little bit: 要使用它,只需稍微修改一下代码:

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

    public TestClass()
    {
        var type = GetType();

        type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
            .ToList()
            .ForEach(f => {
                f.SetValue(this, Activator.CreateInstance(f.FieldType);
            });
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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