C# 为什么对更改的字段使用只读修饰符?
在Josh Smith的教程中,字段定义为只读:C# 为什么对更改的字段使用只读修饰符?,c#,modifier,C#,Modifier,在Josh Smith的教程中,字段定义为只读: public class CustomerRepository { readonly List<Customer> _customers; ... public CustomerRepository(string customerDataFile) { _customers = LoadCustomers(customerDataFile); } ...
public class CustomerRepository
{
readonly List<Customer> _customers;
...
public CustomerRepository(string customerDataFile)
{
_customers = LoadCustomers(customerDataFile);
}
...
}
这是如何允许的以及使用readonly有什么意义?列表变量本身是只读的\u customers是只读的-这意味着您不能将其切换到完全不同的列表,以确保查看它的每个人都将始终看到相同的列表。但是,您仍然可以更改该列表中的元素。来自MSDN:
readonly关键字是可以在字段上使用的修饰符。当字段声明包含只读修饰符时,对该声明引入的字段的赋值只能作为声明的一部分或在同一类的构造函数中发生
您不能将新值分配给_customers字段,但仍然可以更改该列表中的元素。\u customers.Addcustomer;不更新列表。此操作员更新列表的内容。如果你想更新列表,你必须使用像_customers=。。。。这是只读的阻止的。使字段为只读的目的是不能更改引用。这意味着你不能写这样的东西
_customers = null;
或
调用method.Add通过方法访问集合,并且不更改对象的引用
这可能有助于防止任何NullReferenceException。如果它是一个对象,我能为它的属性设置新值吗?@Saeid Yes-你没有修改变量的值,因此你没有违反readonly修饰符。
_customers = null;
_customers = new List<Customer>();