Why Automatically implemented properties must define both get and set accessors

前端 未结 3 1815
-上瘾入骨i
-上瘾入骨i 2020-12-15 03:12

When we define a property like

    public string Name {get; set;}

dot net can make our properties code. but when we use

            


        
相关标签:
3条回答
  • 2020-12-15 03:48

    Because the auto-implemented properties generate their own backing store for the property values. You have no access to the internal store.

    Implementing a property with

    • just get : means you can only retrieve the values. You can't ever set the property value (even in the containing class)
    • just set : means you can only set the values. You can't retrieve the property value.

    for a normal property

    private int _data;
    public int Data{  get { return _data } };
    

    Here the parent class can do the following somewhere else in the class ( which it can't with auto props)

    _data = 100;

    Note: You can define an auto-prop like this (which is how I use it the most).

    public int Data { get; private set;}
    

    This means that the property can't be set by external clients of the class. However the containing class itself can set the property multiple times via this.Data = x; within the class definition.

    0 讨论(0)
  • 2020-12-15 04:01

    If there is no setter, the property can never have anything other than the default value, so doesn't serve any purpose.

    0 讨论(0)
  • 2020-12-15 04:13

    A more modern scenario for receiving this error is building code that uses C#6 syntax using a version of VisualStudio that is less than VS 2015 (or using MsBuild that is less than 14).

    In C#6.0 it is allowable to have autoProperties that do not have a setter (they are assumed to be a private set).

    Try compiling with VS2015+ or msbuild 14+ .. or modify the code so that all autoProperties have a setter.

    0 讨论(0)
提交回复
热议问题