实现与{获得只读属性; } [英] Implementing read-only properties with { get; }

查看:159
本文介绍了实现与{获得只读属性; }的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么没有这样运行:

 类节目
{
静态无效的主要(字符串[]参数)
{
苹果=新的苹果(绿色);
}
}

类苹果
{

公共字符串颜色{搞定; }

公共苹果(串色)
{
this.Colour =颜色;
}

}


解决方案

您的代码是有效的C#6,附带的Visual Studio 2015是的的有效的语言或Visual Studio的早期版本。从技术上讲,你可以在VS 2013安装罗斯林的老预发行版本,但现在的麻烦VS 2015发布不值得。



有关此问题发生,任你使用Visual Studio的错误版本编译C#代码6,或者你正试图从编译使用错误的开发环境 - 即在命令行代码,你的路径指向旧的编译器。也许你于2013年开发命令提示符,而不是2015年开了?



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



如果你要使用Visual Studio 2013年或更老,你必须改变你的代码,使用较旧的语法,例如:

 公共只读字符串_colour; 

公共字符串颜色{{返回_colour;}}

公共苹果(串色)
{
_colour =颜色;
}

 公共字符串颜色{搞定;私人集;} 

公共苹果(串色)
{
颜色=颜色;
}

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



注意



您可以使用Visual Studio 2015年的目标.NET 4.5。语言和运行时的是两回事的。真正的要求是编译器必​​须的语言版本


匹配

Why doesn't this run:

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

  }

解决方案

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.

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?

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

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

or

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

NOTE

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

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

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