【问题标题】:What is the equivalent for expression-bodied members in old C# versions?旧 C# 版本中表达式主体成员的等价物是什么?
【发布时间】:2022-01-09 21:23:27
【问题描述】:

我最近发现在新版本的 C# 中存在所谓的表达式体成员,如 here 所述。

表达式主体成员的示例是(仅适用于 getter 属性):

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

上面的表达式主体成员是否等同于旧的 C# 版本?

private int _x;
public int X
{
    get
    {
       return _x;
    }
}

【问题讨论】:

  • 它们并不是什么“新东西”——它们从大约十年前的 C# 6.0 就已经存在了。
  • 每当你想知道一个特性是否编译相同时,只要问 Sharplab sharplab.io/…
  • @Martheen 很棒的工具!非常感谢。我不知道。从现在开始我会考虑的。
  • @Dai Ops,直到现在我才听说它;)

标签: c# properties getter expression-bodied-members


【解决方案1】:

这些都是等价的:

private int _x;
public int X => _x;

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

private int _x;
public int X
{
    get
    {
        return _x;
    }
}

【讨论】:

  • 还有public int X {get;}
  • 你是对的,但前提是你从不使用 _x 字段。
【解决方案2】:

是的,这些表达式是等价的。因为表达式主体成员的作用相同,但仅针对单个表达式。

【讨论】:

  • 你说“但只针对单个表达式”是什么意思?
  • 我的意思是只包含一行代码的表达式。你可以把它放到没有代码块的方法中。
猜你喜欢
  • 2014-08-23
  • 2016-04-09
  • 2010-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多