简体   繁体   English

用=>初始化(这样)

[英]Initialization with => (such that)

I've been looking into Entity Framework 7 source code on github and I've found following property initialization in TableExpressionBase.cs 我一直在寻找github上的Entity Framework 7源代码,我在TableExpressionBase.cs中发现了以下属性初始化

public override ExpressionType NodeType => ExpressionType.Extension;

I have never seen such usage of => operator in C#. 我从来没有在C#中看到过=>运算符的用法。 I've also looked what is new in C# 6.0, however I haven't found this construct. 我也看了C#6.0中的新内容,但是我没有找到这个结构。 Can someone explain what is the purpose of it? 有人可以解释它的目的是什么?

Thanks. 谢谢。

This is the new expression-bodied members syntax that was added in C# 6.0. 这是在C#6.0中添加的新的表达式成员语法。

This article has a good rundown of the things that was added, look for the heading "Expression Bodied Functions and Properties" about 3/4 down the article. 本文对所添加的内容有一个很好的概述,在文章的下方3/4处寻找标题“表达身体功能和属性”。

In C# 6.0 a lot of syntax was added that generates code under the hood. 在C#6.0中,添加了很多语法,可以生成代码。 It doesn't allow you to do stuff that you couldn't do before, but it makes the number of lines of code you have to write smaller. 它不允许你做你以前不能做的事情,但它会使你必须编写的代码行数变小。

Specifically, if you have a property like this: 具体来说,如果您有这样的属性:

public TYPE Name
{
    get
    {
        return EXPRESSION;
    }
}

Then you can now write this property like this: 然后你现在可以这样写这个属性:

public TYPE Name => EXPRESSION;

The compiled code will be identical so you can pick and choose which one of the two syntax variations you want to use. 编译后的代码将完全相同,因此您可以选择要使用的两种语法变体中的哪一种。

You can do the same thing with methods: 你可以用方法做同样的事情:

public string Name(int PARAM1, string PARAM2)
{
    return string.Format("{0}, {1}", PARAM1, PARAM2);
}

can become: 可以变成:

public string Name(int PARAM1, string PARAM2) => string.Format("{0}, {1}", PARAM1, PARAM2);

That's all there is to it. 这里的所有都是它的。

Specifically, the property you saw in the EF7 code is basically the same as this: 具体来说,您在EF7代码中看到的属性与此基本相同:

public override ExpressionType NodeType
{
    get
    {
        return ExpressionType.Extension;
    }
}

It's a new C# 6.0 feature as you suspected. 这是您怀疑的新C#6.0功能。

Properties and indexers can have getters and settersgetter-only properties and indexers can have an expression body: 属性和索引器可以有getter和settersgetter-only属性,索引器可以有一个表达式主体:

 public string Name => First + " " + Last; public Customer this[long id] => store.LookupCustomer(id); 

http://blogs.msdn.com/b/csharpfaq/archive/2014/11/20/new-features-in-c-6.aspx http://blogs.msdn.com/b/csharpfaq/archive/2014/11/20/new-features-in-c-6.aspx

Its simply a shorter way to define a getter for a property. 它只是一种为物业定义吸气剂的简短方法。

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

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