The*_*ght 4 c# asp.net properties readonly
如下所示,用户可以更改只读产品字段/属性:
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 };
}
}
Run Code Online (Sandbox Code Playgroud)
我认为这很基本,但似乎并非如此.
如何在C#中创建只读对象属性或字段?
谢谢,
该readonly关键字阻止您将新实例放入该字段.
它不会神奇地使字段内的任何对象不可变.
如果你写的话,你期望发生什么?
readonly Product x = Product.Create();
Product y;
y = x;
y.Name = "Changed!";
Run Code Online (Sandbox Code Playgroud)
如果你想要一个不可变对象,你需要通过删除所有公共setter使类本身不可变.
您需要将Product的Name属性设置为private:
public class Product
{
private Product(){}
public string Name { get; private set; }
public static Product Create(string name)
{
return new Product { Name = name };
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6724 次 |
| 最近记录: |