使用Property" get {}"," set {}"是否有任何差异或" =>" C#中的语法?

时间:2017-10-22 13:31:18

标签: c# .net compiler-construction roslyn .net-runtime

Code_1(此代码使用" =>",为什么这两个代码都有相同的结果)

public class Infor<TFirst, TSecond, TThird>
{
    private TFirst first;
    private TSecond second;
    private TThird third;

    public TThird Third { get => third; set => third = value; }
    public TSecond Second { get => second; set => second = value; }
    public TFirst First { get => first; set => first = value; }
}

Code_2(此代码使用&#34;返回&#34;不&#34; =&gt;&#34;)

public class Infor<TFirst, TSecond, TThird>
{
    private TFirst first;
    private TSecond second;
    private TThird third;

    public TThird Third { get { return third; } set { third = value; } }
    public TSecond Second { get { return second; } set { second = value; } }
    public TFrist First { get { return first; } set { first = value; } }
}

3 个答案:

答案 0 :(得分:4)

没有差异。内部C#编译器将MyProperty { get {set {语法转换为编译器发出的方法,具有以下签名和实现:

TFirst get_MyProperty() { return first;}
void set_MyProperty(TFirst value) { first = value; }

=>语法称为expression bodied property accessors的情况也是如此。 =>的用法仅仅是syntactic sugar,它是为了简化编码和减少必须重复编写的样板代码而创建的。

答案 1 :(得分:3)

这两个代码示例之间没有区别。 这也适用于函数,如果您只有一个内部操作,其结果可以立即从函数返回。例如:

int Method(int x)
{
    return x;
}

相当于:

int Method(int x) => x;

答案 2 :(得分:1)

可以处理它的编译器存在差异。

Expression bodied属性访问器是C#7功能。因此,例如,C#6编译器会将其视为错误。