“=>”运算符在 C# 中的 属性 中意味着什么?

What does "=>" operator mean in a property in C#?

这个代码是什么意思?

public bool property => method();

这是一个 表达式主体 属性,一种在 C# 6 中引入的计算属性的新语法,它允许您以与您相同的方式创建计算属性将创建一个 lambda 表达式。此语法等同于

public bool property {
    get {
        return method();
    }
}

类似的语法也适用于方法:

public int TwoTimes(int number) => 2 * number;

这是一个浓郁的表达 属性。例如,参见 MSDN。 这只是 shorthand for

public bool property
{
    get
    {
        return method();
    }
}

表达式主体函数也是可能的:

public override string ToString() => string.Format("{0}, {1}", First, Second);

这是一个浓郁的表达属性。它可以用作 属性 吸气剂或方法声明的简化。 从 C# 7 开始,它还扩展到其他成员类型,如构造函数、终结器、属性 setter 和索引器。

查看 MSDN 文档了解更多信息。

"Expression body definitions let you provide a member's implementation in a very concise, readable form. You can use an expression body definition whenever the logic for any supported member, such as a method or property, consists of a single expression."

是表达体化的简化。

public string Text =>
  $"{TimeStamp}: {Process} - {Config} ({User})";

参考; https://msdn.microsoft.com/en-us/magazine/dn802602.aspx

在 属性 中使用的

=> 是一个 expression body。基本上是用 getter 编写 属性 的一种更短更简洁的方法。

public bool MyProperty {
     get{
         return myMethod();
     }
}

翻译成

public bool MyProperty => myMethod();

它更加简单易读,但您只能在 C# 6 中使用此运算符,here您将找到有关表达式主体的特定文档。

正如一些人提到的,这是 C# 6 首次引入的新功能,他们在 C# 7.0 中扩展了它的用法以将其与 getter 和 setter 一起使用,您还可以将表达式主体语法与如下方法一起使用:

static bool TheUgly(int a, int b)
{
    if (a > b)
        return true;
    else
        return false;
}
static bool TheNormal(int a, int b)
{
    return a > b;
}
static bool TheShort(int a, int b) => a > b; //beautiful, isn't it?