使用反射初始化构造函数中的(列表)属性 [英] Initializing (list) properties in constructor using reflection

查看:50
本文介绍了使用反射初始化构造函数中的(列表)属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用反射来初始化类(列表)中的所有属性:

I am trying to initialize all properties in class (lists) with using reflection:

public class EntitiesContainer
{
    public IEnumerable<Address> Addresses { get; set; }
    public IEnumerable<Person> People { get; set; }
    public IEnumerable<Contract> Contracts { get; set; }

    public EntitiesContainer()
    {
        var propertyInfo = this.GetType().GetProperties();
        foreach (var property in propertyInfo)
        {
            property.SetValue(property, Activator.CreateInstance(property.GetType()), null);
        }
    }
}

我遇到异常:

没有为该对象定义没有参数的构造函数.

No constructor has been defined for this object without parameters.

我将感谢提示.

推荐答案

只要您将属性定义为具体类型,您就可以做到 .这实际上有效:

You can do this provided that you define the properties as concrete types. This actually works:

public class EntitiesContainer
{
    public List<Address> Addresses { get; set; }
    public List<Person> People { get; set; }
    public List<Contract> Contracts { get; set; }

    public EntitiesContainer()
    {
        var propertyInfo = this.GetType().GetProperties();
        foreach (var property in propertyInfo)
        {
            property.SetValue(this, Activator.CreateInstance(property.PropertyType));
        }
    }
}

您不能创建 IEnumerable< T> 的实例,因为它是接口.

You cannot create an instance of an IEnumerable<T> because it's an interface.

但是您为什么要这么做?您最好使用C#6中引入的自动属性初始化程序来初始化属性:

But why would you want to to this? You'd better initialize the properties using the auto-property initializer that was introduced in C#6:

public class EntitiesContainer
{
    public IEnumerable<Address> Addresses { get; set; } = new List<Address>;
    public IEnumerable<Person> People { get; set; } = new List<Address>;
    public IEnumerable<Contract> Contracts { get; set; } = new List<Address>;
}

这篇关于使用反射初始化构造函数中的(列表)属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆