正如下面可以看到,用戶能夠改變只讀產品字段/屬性:如何在C#中創建只讀對象屬性?
class Program
{
static void Main(string[] args)
{
var product = Product.Create("Orange");
var order = Order.Create(product);
order.Product.Name = "Banana"; // Main method shouldn't be able to change any property of product!
}
}
public class Order
{
public Order(Product product)
{
this.Product = product;
}
public readonly Product Product;
public static Order Create(Product product)
{
return new Order (product);
}
}
public class Product
{
private Product(){}
public string Name { get; set; }
public static Product Create(string name)
{
return new Product { Name = name };
}
}
我認爲這是很基本的,但它似乎並非如此。
如何在C#中創建一個只讀對象屬性或字段?
感謝,
相關:[爲什麼微軟建議對可變值的只讀字段?](http://stackoverflow.com/questions/2804805/why-does-microsoft-advise-against-readonly-fields-with-mutable-values/2804850#2804850) –