这个奇怪的 C# 语法是什么?我该如何构建它?

What's this strange C# syntax and how do I build it?

在看项目的时候,发现了一些奇怪的C#代码:

public class F : IElement
{
    public int CurrentHp { get; } = 10;
    public bool IsDead => CurrentHp <= 0;
}

通常我会这样写:

public class F : IElement
{
    public const int CurrentHp = 10;
    public bool IsDead
    {
        get { return CurrentHp <= 0; }
    }
}

我的Visual Studio 2013也认不出第一个例子

这是什么语法,我应该怎么做才能使这个项目可构建?

C# 6 的特点: New Language Features in C# 6.

第一个

public int CurrentHp { get; } = 10;

Getter-only auto-propertiey

第二个

public bool IsDead => CurrentHp <= 0;

Expression bodies on property-like function members

=> 是 C# 6 中的新运算符,表示要用于 getter.

Expression Bodied Function

就编译器而言,您的两个示例是同义词,只是 return 分配的值。 => 语法糖 使开发更容易一些并且需要更少的代码行来实现相同的结果。

但是,您将无法编译,除非您使用最新的编译器版本更新到 VS2015。

编辑:

正如 Philip Kendall 和 Carl Leth 在评论中所说,每行的第一行并不是 完全 的同义词,因为 public const int CurrentHp = 10; 是一个字段并且 public int CurrentHp { get; } = 10; 是 属性。虽然在高层次上结果是相同的(将 10 的值分配给 CurrentHp 而 属性 只能在 class 构造函数中设置),但它们的不同之处在于:

With const int CurrentHp = 10, CurrentHp will always be 10, take up 4 total bytes, and can be accessed statically. int CurrentHp { get; } = 10defaults to 10, but can be changed in the constructor of F and thereby can be different per instance and cannot be accessed statically.

正如其他人所说,这是新的 C# 6 功能。在 1

查看完整列表

然而,在 C# 6 之前,这将更正确地转换为:

public class F : IElement
{
    public int CurrentHp { get; private set };
    public bool IsDead { get { return CurrentHp <= 0; } }
    public F() { CurrentHp = 10; }
}

New Language Features in C# 6

如果您使用 C# 6,这是您的代码:

public bool IsDead => CurrentHp <= 0;

它只是一个 属性 和一个 get,如果使用这个运算符 =>

在早期的版本中你会这样写:

public bool IsDead { get { return CurrentHp <= 0; } }