ジョシュ・スミスthisチュートリアルでは、フィールドは読み取り専用として定義されます。これが許される方法変更するフィールドで読み取り専用修飾子を使用するのはなぜですか?
public void AddCustomer(Customer customer)
{
if (customer == null)
throw new ArgumentNullException("customer");
if (!_customers.Contains(customer))
{
_customers.Add(customer);
if (this.CustomerAdded != null)
this.CustomerAdded(this, new CustomerAddedEventArgs(customer));
}
}
をし、ポイントは何ですか:
public class CustomerRepository
{
readonly List<Customer> _customers;
...
public CustomerRepository(string customerDataFile)
{
_customers = LoadCustomers(customerDataFile);
}
...
}
以降読み取り専用リスト、_customers
を、更新され、 readonlyを使うのは?
オブジェクトであれば、そのプロパティに新しい値を設定できますか? – Saeid
@Saeidはい - そうしている変数の値を変更していないので、 'readonly'修飾子に違反していません。 –