简体   繁体   English

空获取表达式身体语法?

[英]empty get in expression bodied syntax?

Is it possible to write this property: 是否可以编写以下属性:

string Error { get; }

in expression bodied syntax ( => ), 在表达式中使用强壮的语法( => ),

for example: 例如:

 string Title
  { 
    get
      {
        return title;
      }
  }

becomes: 变成:

string Title => title;

No, because this: 不,因为:

string Error { get; }

... is an automatically-implemented property. ...是自动实现的属性。 The compiler is generating a field for you behind the scenes, but you can't refer to that field within the code. 编译器正在幕后为您生成一个字段,但是您不能在代码中引用该字段。 If you need to use the backing field, you need to declare it yourself: 如果需要使用支持字段,则需要自己声明:

private readonly string error;
string Error => error;

That's basically what the compiler is generating for you - so if you want that, just write it yourself. 基本上这就是编译器为您生成的内容-因此,如果您愿意,只需自己编写即可。 It's pretty rare that that's useful though, IMO. IMO很少有用。

If you already have that field, you could either just write the property as above, or you could convert the field into the property, so use the property where you were previously using the field. 如果已经有了该字段,则可以如上所述编写属性,也可以将字段转换为该属性,因此请使用以前使用该字段的属性。

(It's more feasible if you want a property which is read-only, but backed by a mutable field - at which point it can't be auto-implemented if you want a genuinely read-only property. It could be a publicly-readable and privately-writable automatically-implemented property though.) (如果您想要一个只读的属性,但要有一个可变字段作为支持,那么这是更可行的方法;在这种情况下,如果您想要一个真正的只读属性,则不能自动实现它。它可以是公开可读的以及可自动写入的私有属性。)

Yes, you can in C# 6.0 . 是的,您可以在C#6.0中使用 But you would still need to declare the backing field yourself: 但是您仍然需要自己声明支持字段:

string error;
string Error => error;

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

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