这个问题在评论想出了这个答案.建议不能使用只读属性作为使用字段而不是属性的潜在原因.
例如:
class Rectangle
{
private readonly int _width;
private readonly int _height;
public Rectangle(int width, int height)
{
_width = width;
_height = height;
}
public int Width { get { return _width; } }
public int Height { get { return _height; } }
}
Run Code Online (Sandbox Code Playgroud)
但为什么你不能这样做呢?
public int Width { get; readonly set; }
Run Code Online (Sandbox Code Playgroud)
编辑(澄清):您可以在第一个示例中实现此功能.但是为什么你不能用自动实现的属性速记来做同样的事情呢?它也不会那么混乱,因为你不必直接访问构造函数中的字段; 所有访问都将通过该属性.
编辑(更新):从C#6.0开始,支持只读属性!object MyProp { get; }此属性可以设置为inline(object MyProp { get; } = ...)或构造函数,但不能设置其他地方(就像readonly字段一样).
为什么不运行:
class Program
{
static void Main(string[] args)
{
Apple a = new Apple("green");
}
}
class Apple
{
public string Colour{ get; }
public Apple(string colour)
{
this.Colour = colour;
}
}
Run Code Online (Sandbox Code Playgroud) 当我尝试从类对象中检索值时,会弹出此错误.它是在get-only属性中实现readonly关键字之后显示的.到目前为止我所理解的是,实现"readonly"只会将class属性限制为get方法.我不太确定如何实现关键字,有些帮助吗?
这是当前的代码.
class Counter
{
private int _count;
private string _name;
public Counter(string name)
{
_name = name;
_count = 0;
}
public void Increment()
{
_count++;
}
public void Reset()
{
_count = 0;
}
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
public readonly int Value
{
get
{
return _count;
}
}
}
Run Code Online (Sandbox Code Playgroud)