![](/img/trans.png)
[英]C# public variable as writeable inside the class but readonly outside the class
[英]Are C# readonly field's allowed to be modify outside of the class?
我有一个通过构造函数参数设置的readonly
对象字段。 如果我修改对象,类里面的字段也会改变,我猜是引用调用。 有什么办法可以做得更好/防止它吗?
private void Form1_Load(object sender, EventArgs e)
{
Product p = new Product() { Name="New" };
Store s = new Store(p);
p.Name = "MODIFY!";
MessageBox.Show(s.Show());//MODIFY!
}
public class Store
{
private readonly Product product;
public Store(Product product)
{
this.product = product;
}
public string Show()
{
return this.product.Name;
}
}
public class Product
{
public string Name { get; set; }
}
您在readonly
字段中存储的是reference 。 当然,该引用是只读的,永远不会改变。 但是引用对象的内容仍然可以更改。
由于Product
似乎是一个数据保存类,一种方法可能是简单地将内容复制到一个新实例中:
public class Store
{
private readonly Product product;
public Store(Product product)
{
// Create a new Product instance that only this Store instance
// knows about
this.product = new Product { Name = product.Name };
}
}
现在只要不导出此实例, Store.product
的内容就无法从外部更改。
但要注意里面的代码Store
类仍然可以改变的内容。
如果您不希望Store
内的product
在更改原始实例时发生更改,则必须在将其分配给字段之前进行复制:
public Store(Product product)
{
this.product = new Product() {Name = product.Name};
}
或者,您可以使Product
成为一个结构体。 传递给方法时总是复制结构,而不是通过引用传递:
public struct Product
{
public string Name { get; set; }
}
另一种选择是创建产品的不可变版本:
public class Product
{
public string Name { get; set; }
public Immutable ToImmutable() => new Immutable(this);
public class Immutable
{
public Immutable(Product product) { Name = product.Name; }
public string Name { get; }
}
}
而现在,
public class Store
{
private readonly Product.Immutable product;
public Store(Product product)
{
this.product = product.ToImmutable();
}
public string Show()
{
return this.product.Name;
}
}
好处? 没有人可以在Store
内乱搞product
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.