请参阅在对象初始值设定项中初始化的对象的其他属性

时间:2015-01-12 15:29:00

标签: c#

创建以下对象时:

var customers = new Customers
{
    Persons = new List<Person>
    {
        new Person { CustomId = "111" },
        new Person { CustomId = "222" }
    },
    Organizations = new List<Organization>
    {
        new Organization { CustomId = "333" }
    },
    Keys = new HashSet<string> { "111", "222", "333" }
};

我想更改Keys的初始化以使用Person [0] .CustomId,Person [1] .CustomId和Organization [0] .CustomId中的先前值。 (不像这样硬编码&#34; 111&#34;,&#34; 222&#34;,&#34; 333&#34;)

在这种初始化中是否有一种简单的方法可以做到这一点?我可以在客户初始化后添加密钥,如下所示:

foreach (var person in customers.Persons)
{
    customers.Keys.Add(person.CustomId);
}
foreach (var org in customers.Organizations)
{
    customers.Keys.Add(org.CustomId);
}

但我无法在与客户相同的初始化中从人员和组织属性创建密钥?

2 个答案:

答案 0 :(得分:5)

No, you can't do that

您可以先创建收藏集,然后concatenate the selected keys

var persons = new List<Person>
{
    new Person { CustomId = "111" },
    new Person { CustomId = "222" }
};

var organizations = new List<Organization>
{
    new Organization { CustomId = "333" }
};

var keys = persons.Select(p => p.CustomId)
                  .Concat(organizations.Select(o => o.CustomId));

var customers = new Customers
{
    Persons = persons,
    Organizations = organizations,
    Keys = new HashSet<string>(keys),
}

但正如其他人所说,这个实施还存在更多问题。您是否希望将此语法用于Customers类的每个使用者?您如何使密钥集合与人员和组织集合保持同步,例如当您添加或删除项目时?

public class Customers
{
    public List<Person> Persons { get; set; }
    public List<Organization> Organizations { get; set; }

    public Customers()
    {
        Persons = new List<Person>();
        Organizations = new List<Organization>();
    }

    public Customers(IEnumerable<Person> persons,
                     IEnumerable<Organization> organizations)
        : this()
    {
        Persons.AddRange(persons);
        Organizations.AddRange(organizations);
    }

    public IEnumerable<string> Keys
    {
        return Persons.Select(p => p.CustomId)
                      .Concat(Organizations.Select(o => o.CustomId));
    }
}

然后,呼叫网站可能如下所示:

var persons = new List<Person>
{
    new Person { CustomId = "111" },
    new Person { CustomId = "222" }
};

var organizations = new List<Organization>
{
    new Organization { CustomId = "333" }
};

var customers = new Customers(persons, organizations);
var keys = customers.Keys;

答案 1 :(得分:0)

将密钥转换为公共财产,例如:

public HashSet<string> Keys
{
   get
   {
      // create and return a new hashset from persons and organizations
   }    
}

这样您就不必考虑更新您的密钥会员。