代码之家  ›  专栏  ›  技术社区  ›  whytheq

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

  •  5
  • whytheq  · 技术社区  · 10 年前

    为什么不运行:

      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;
        }
    
      }
    
    4 回复  |  直到 10 年前
        1
  •  9
  •   Community Mohan Dere    8 年前

    您的代码对Visual Studio 2015附带的C#6有效 对该语言或Visual Studio的早期版本有效。从技术上讲,你可以在VS 2013中安装一个旧的Roslyn预发布版本,但现在VS 2015发布了,这不值得麻烦。

    要出现此问题,要么您使用了错误的Visual Studio版本来编译C#6代码,要么您试图使用错误的开发环境从命令行编译代码,即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为目标 are two different things 。真正的要求是编译器必须与语言版本匹配

        2
  •  4
  •   MakePeaceGreatAgain    10 年前

    向属性中添加私有setter:

    public string Colour{ get; private set;}
    

    或添加只读备份字段:

    private string _colour;
    public string Colour{ get return this._colour; }
    
    public Apple(string colour)
    {
      this._colour = colour;
    }
    
        3
  •  2
  •   Oliver Gray    10 年前

    我认为你想要的是这个,它只通过向外界公开GET来保护你的内部变量。为了额外的安全,您可以将_color标记为只读,以便它也不能在类本身内更改(实例化后),但我认为这是过分的。如果你的苹果变老了,需要变成棕色怎么办?!

    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;
        }
    
    }
    
        4
  •  1
  •   Dr Rob Lang Matthew Abbott    10 年前

    这里有两个选项:

    // 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;
    }
    
    推荐文章