简体   繁体   English

用于属性的 getter 和 setter 的 Lambda

[英]Lambda for getter and setter of property

In C# 6.0 I can write:在 C# 6.0 中,我可以这样写:

public int Prop => 777;

But I want to use getter and setter.但我想使用 getter 和 setter。 Is there a way to do something kind of the next?有没有办法做一些下一个?

public int Prop {
   get => propVar;
   set => propVar = value;
}

First of all, that is not lambda, although syntax is similar.首先,这不是 lambda,尽管语法相似。

It is called " expression-bodied members ".它被称为“ 表达式体成员”。 They are similar to lambdas, but still fundamentally different.它们与 lambda 相似,但仍然有根本的不同。 Obviously they can't capture local variables like lambdas do.显然,它们不能像 lambda 那样捕获局部变量。 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.此外,与 lambda 不同,它们可以通过它们的名称访问:) 如果您尝试将表达式主体属性作为委托传递,您可能会更好地理解这一点。

There is no such syntax for setters in C# 6.0, but C# 7.0 introduces it . C# 6.0 中没有 setter 的这种语法,但C# 7.0 引入了它

private int _x;
public int X
{
    get => _x;
    set => _x = value;
}

C# 7 brings support for setters, amongst other members: C# 7支持 setter,以及其他成员:

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# 6.0 中很受欢迎,但我们不允许在所有类型的成员中使用它们。 C# 7.0 adds accessors, constructors and finalizers to the list of things that can have expression bodies: C# 7.0 将访问器、构造器和终结器添加到可以具有表达式主体的事物列表中:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM