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

2019-01-31 17:21发布

This question already has an answer here:

What does this code mean?

public bool property => method();

标签: c# c#-6.0
6条回答
兄弟一词,经得起流年.
2楼-- · 2019-01-31 17:53

That's an expression bodied property. See MSDN for example. This is just a shorthand for

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

Expression bodied functions are also possible:

public override string ToString() => string.Format("{0}, {1}", First, Second);
查看更多
手持菜刀,她持情操
3楼-- · 2019-01-31 17:55

It's the expression bodied simplification.

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

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

查看更多
霸刀☆藐视天下
4楼-- · 2019-01-31 18:01

This is an expression-bodied property, a new syntax for computed properties introduced in C# 6, which lets you create computed properties in the same way as you would create a lambda expression. This syntax is equivalent to

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

Similar syntax works for methods, too:

public int TwoTimes(int number) => 2 * number;
查看更多
成全新的幸福
5楼-- · 2019-01-31 18:02

As some mentioned this is a new feature brought first to C# 6, they extended its usage in C# 7.0 to use it with getters and setters, you can also use the expression bodied syntax with methods like this:

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?
查看更多
迷人小祖宗
6楼-- · 2019-01-31 18:05

=> used in property is an expression body. Basically a shorter and cleaner way to write a property with only getter.

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

Is translated to

public bool MyProperty => myMethod();

It's much more simpler and readable but you can only use this operator from C# 6 and here you will find specific documentation about expression body.

查看更多
时光不老,我们不散
7楼-- · 2019-01-31 18:06

That is a expression bodied property. It can be used as a simplification from property getters or method declarations. From C# 7 it was also expanded to other member types like constructors, finalizers, property setters and indexers.

Check the MSDN documentation for more info.

"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."

查看更多
登录 后发表回答