c# - 是否允许在类外修改 C# 只读字段?

标签 c#

我有一个通过构造函数参数设置的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 类中的代码可能仍然能够更改内容。

关于c# - 是否允许在类外修改 C# 只读字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47818243/

相关文章:

c# - Graphics.DrawString() 和比例字体的前导填充空间

c# - 如何确定哪个鼠标按钮引发了 WPF 中的单击事件?

c# - 来自 Eric Lippert 的博客 : "don' t close over the loop variable"

c# - 使用 REST XML Web 服务

c# - Entity Framework : Foreign Key in code first

c# - 一次播放多个声音文件

c# - Entity Framework (EF) 迁移取决于 SQL Server 版本

c# - 如何在 string.Format 中引用数组值?

c# - 为什么我不能在fixed语句中使用extern函数?

c# - 数据绑定(bind)后(在事件处理程序期间)从 RepeaterItem 检索 DataItem