集合类型属性是否需要设置器
//Type 1
class Company
{
private IList<Customer> customers;
public IList<Customer> Customers
{
get { return customers; }
set { customers = value; }
}
}
//Type 2
class Company
{
private readonly IList<Customer> customers = new List<Customer>();
public IList<Customer> Customers
{
get { return customers; }
}
}
何时使用Type 1和Type 2?如果我初始化一个List并使用只读属性Customers,如Company.Customers.Add(new Customer)
,不就足够了吗?
关于为集合类型属性提供setter的最佳实践是什么?