使用 { get; 实现只读属性} [英] Implementing read-only properties with { get; }

查看:29
本文介绍了使用 { 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.它对于该语言的早期版本或无效视觉工作室.从技术上讲,您可以在 VS 2013 中安装旧的 Roslyn 预发布版本,但现在 VS 2015 已发布,这不值得麻烦.

Your code is valid for C# 6, which comes with Visual Studio 2015. It is not valid for previous versions of the language or Visual Studio. Technically, you can install an old pre-release version of Roslyn in VS 2013 but it isn't worth the trouble now that VS 2015 was released.

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

For this problem to occur, either you are using the wrong version of Visual Studio to compile C# 6 code, or you are trying to compile your code from the command line using the wrong development environment -ie, your PATH points to the old compiler. Perhaps you opened the 'Developer Command Prompt for 2013' instead of 2015?

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

You should either compile your code using Visual Studio 2015, or ensure your path variable points to the latest compiler.

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

If you have to use Visual Studio 2013 or older, you'll have to change your code to use the older syntax, eg:

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

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

Note that the second option isn't truly read-only, other members of the class can still modify the property

注意

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

You can use Visual Studio 2015 to target .NET 4.5. The language and the runtime are two different things. The real requirement is that the compiler must match the language version

这篇关于使用 { get; 实现只读属性}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆