在.NET应用程序中,什么时候应该使用"ReadOnly“属性,什么时候应该只使用"Get”。这两者之间的区别是什么。
private readonly double Fuel= 0;
public double FuelConsumption
{
get
{
return Fuel;
}
}
或
private double Fuel= 0;
public double FuelConsumption
{
get
{
return Fuel;
}
}
发布于 2010-04-27 16:31:36
只有一个getter的属性是只读的。原因没有提供setter来更改属性的值(从外部)。
C#有一个关键字readonly,可以在字段(而不是属性)上使用。标记为"readonly“的字段只能在构造对象期间设置一次(在构造函数中)。
private string _name = "Foo"; // field for property Name;
private bool _enabled = false; // field for property Enabled;
public string Name{ // This is a readonly property.
get {
return _name;
}
}
public bool Enabled{ // This is a read- and writeable property.
get{
return _enabled;
}
set{
_enabled = value;
}
}
发布于 2012-11-28 16:24:28
只读属性用于创建故障保护代码。我真的很喜欢Mark Seemann关于属性和支持字段的封装帖子系列:
http://blog.ploeh.dk/2011/05/24/PokayokeDesignFromSmellToFragrance.aspx
取自Mark的例子:
public class Fragrance : IFragrance
{
private readonly string name;
public Fragrance(string name)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
this.name = name;
}
public string Spread()
{
return this.name;
}
}
在本例中,您将使用readonly name字段来确保类不变量始终有效。在这种情况下,类编写者希望确保name字段只设置一次(不可变)并始终存在。
发布于 2010-04-27 16:24:30
方法提示返回值必须发生什么,属性提示该值已经存在。这是一个经验法则,有时你可能需要一个做一些工作的属性(例如Count
),但通常这是一个有用的决定方法。
https://stackoverflow.com/questions/2719699
复制相似问题