简体   繁体   English

C# - 常量属性相当于lambda表达式?

[英]C# - constant property is equivalent to lambda expression?

I picked up C# again, came back after a long work in Java, and as you may expect, I got very interested in properties(oh the Java burden), therefore I started to explore them a bit and came up with this. 我再次拿起C#,经过Java的长期工作后回来,正如你所料,我对属性非常感兴趣(哦,Java负担),因此我开始探索它们并想出了这个。

private static float Width {
    get { return 0.012f; }
}

After a bit of tinkering, I realized this works too(lambda expression?). 经过一些修补,我意识到这也有效(lambda表达式?)。

private static float Width => 0.012f;

Now please help a fellow Java developer here to understand what is exactly the difference? 现在请帮助这里的Java开发人员了解究竟有什么区别? What the former can do that the latter cannot and vice versa. 前者可以做什么,后者不能,反之亦然。

what is exactly the difference? 究竟有什么区别?

Both ways define a getter only property. 两种方式都定义了一个getter only属性。 The latter simply uses C# 6's new feature called "Expression Bodied Members" , specifically these are "Expression Bodied Properties", which allow you to use the fat arrow syntax and are merely syntax sugar. 后者只是使用C#6的新功能“Expression Bodied Members” ,特别是“Expression Bodied Properties”,它们允许你使用胖箭头语法,只是语法糖。

If you look at what the compiler generates , you'll see: 如果你看一下编译器生成的内容 ,你会看到:

private static float Width
{
    get
    {
        return 0.012f;
    }
}

Which is identical to your getter only declaration. 这与您的getter only声明相同。

These can also be applied to one-liner methods as well: 这些也可以应用于单线方法:

public int Multiply(int x) => x * x;

There are equal. 有平等的。

private static float Width => 0.012f;

The Width is a getter only property just like your first example; Width是一个只有getter的属性,就像你的第一个例子;
The difference is merely only syntactic sugar. 区别仅在于语法糖。

ref: https://github.com/dotnet/roslyn/wiki/Languages-features-in-C%23-6-and-VB-14 参考: https//github.com/dotnet/roslyn/wiki/Languages-features-in-C%23-6-and-VB-14

This is a simplification of the language under C# 6.0 and are called 'Expression Bodied Functions / Properties'. 这是C#6.0下语言的简化,称为“表达身体功能/属性”。

The idea is to simplify the syntax and allow you to set values for functions and properties in a shorter format. 我们的想法是简化语法,并允许您以更短的格式设置函数和属性的值。

Visual Studio magazine has an article on it here: https://visualstudiomagazine.com/articles/2015/06/03/c-sharp-6-expression-bodied-properties-dictionary-initializer.aspx Visual Studio杂志上有一篇文章: https//visualstudiomagazine.com/articles/2015/06/03/c-sharp-6-expression-bodied-properties-dictionary-initializer.aspx

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

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