Lambda用于财产的获取和设定 [英] Lambda for getter and setter of property

查看:99
本文介绍了Lambda用于财产的获取和设定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#6.0中,我可以编写:

In C# 6.0 I can write:

public int Prop => 777;

但是我要使用getter和setter。
是否可以执行下一个操作?

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

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


推荐答案

首先,即不是lambda,尽管语法相似。

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

它称为 表达式主体成员。它们与lambda相似,但仍存在根本差异。显然,它们无法像lambdas那样捕获局部变量。另外,与lambda不同,它们可以通过其名称访问:)如果尝试将表达式健全的属性作为委托进行传递,您可能会更好地理解这一点。

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.

C#6.0中没有针对setter的此类语法,但 C#7.0引入了它

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

这篇关于Lambda用于财产的获取和设定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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