使用{get;实现只读属性 }

为什么不运行:

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; } } 

您的代码适用于Visual Studio 2015附带的C#6。它对以前版本的语言或Visual Studio无效。 从技术上讲,您可以在VS 2013中安装旧的预发布版本的Roslyn,但现在VS 2015发布并不值得。

要发生此问题,要么使用错误版本的Visual Studio来编译C#6代码,要么尝试使用错误的开发环境从命令行编译代码-ie,您的PATH指向旧编译器。 也许您打开了“2013年开发人员命令提示”而不是2015年?

您应该使用Visual Studio 2015编译代码,或者确保路径变量指向最新的编译器。

如果必须使用Visual Studio 2013或更早版本,则必须更改代码以使用旧语法,例如:

 public readonly string _colour; public string Colour { get {return _colour;}} public Apple(string colour) { _colour=colour; } 

要么

 public string Colour {get; private set;} public Apple(string colour) { Colour=colour; } 

请注意,第二个选项不是真正的只读,该类的其他成员仍然可以修改该属性

注意

您可以使用Visual Studio 2015来定位.NET 4.5。 语言和运行时是两回事 。 真正的要求是编译器必须与语言版本匹配

要么为您的酒店添加私人二手商店:

 public string Colour{ get; private set;} 

或者添加一个只读后备字段:

 private string _colour; public string Colour{ get return this._colour; } public Apple(string colour) { this._colour = colour; } 

我认为你正在寻找的是这个,它通过仅向外界暴露GET来保护你的内部变量。 为了更加安全,您可以将_colour标记为只读,以便它不能在类本身内进行更改(在实例化之后),但我认为这有点过分。 如果你的苹果老了需要变成棕色怎么办?

 class Program { static void Main(string[] args) { Apple a = new Apple("green"); } } class Apple { private string _colour; public string Colour { get { return _colour; } } public Apple(string colour) { this._colour = colour; } } 

你有几个选择:

 // Make the string read only after the constructor has set it private readonly string colour public string Colour { get { return colour; } } public Apple(string colour) { this.colour = colour; } // Make the string only readonly from outside but editing from within the class public string Colour { get; private set; } public Apple(string colour) { this.Colour= colour; }