Lambda for getter and setter of property

前端 未结 3 1697
孤独总比滥情好
孤独总比滥情好 2020-12-02 16:17

In C# 6.0 I can write:

public int Prop => 777;

But I want to use getter and setter. Is there a way to do something kind of the next?

相关标签:
3条回答
  • 2020-12-02 16:55

    There is no such syntax, but the older syntax is pretty similar:

        private int propVar;
        public int Prop 
        {
            get { return propVar; }
            set { propVar = value; }
        }
    

    Or

    public int Prop { get; set; }
    
    0 讨论(0)
  • 2020-12-02 16:58

    C# 7 brings support for setters, amongst other members:

    More expression bodied members

    Expression bodied methods, properties etc. are a big hit in C# 6.0, but we didn’t allow them in all kinds of members. C# 7.0 adds accessors, constructors and finalizers to the list of things that can have expression bodies:

    class Person
    {
        private static ConcurrentDictionary<int, string> names = new ConcurrentDictionary<int, string>();
        private int id = GetId();
    
        public Person(string name) => names.TryAdd(id, name); // constructors
        ~Person() => names.TryRemove(id, out _);              // finalizers
        public string Name
        {
            get => names[id];                                 // getters
            set => names[id] = value;                         // setters
        }
    }
    
    0 讨论(0)
  • 2020-12-02 17:00

    First of all, that is not lambda, although syntax is similar.

    It is called "expression-bodied members". They are similar to lambdas, but still fundamentally different. Obviously they can't capture local variables like lambdas do. Also, unlike lambdas, they are accessible via their name:) You will probably understand this better if you try to pass an expression-bodied property as a delegate.

    There is no such syntax for setters in C# 6.0, but C# 7.0 introduces it.

    private int _x;
    public X
    {
        get => _x;
        set => _x = value;
    }
    
    0 讨论(0)
提交回复
热议问题