C#成员属性只写了一个get结果报错

一个简单的问题。如图所示

clipboard.png
错误信息:Error 1 'ConsoleApplication1.A.Template.get' must declare a body because it is not marked abstract or extern. Automatically implemented properties must define both get and set accessors. d:documentsvisual studio 2013ProjectsConsoleApplication1ConsoleApplication1Program.cs 22 34 ConsoleApplication1

我只写了一个get 结果报错 。但是下面这个却没有问题:

clipboard.png

本人刚接触C# 手头上 也没有书籍 。 也并非伸手党,查过此问题,没查着。还望各位大神们不吝赐教。

阅读 5.4k
3 个回答

VS2013会报错,VS2017不报错,在VS2013中想实现只有Get的就用原来的字段方式,或者在set前面加private
{ get; private set; }

截至 C# 5.0, 自动实现的属性必须同时具有 get 和 set 访问器:

由于支持字段不可访问,因此只能通过属性访问器对其进行读写,即使在包含类型中也是如此。这意味着自动实现的只读或只写属性没有意义,且不允许使用这两种属性。

— C# Language Specification 5.0

但是 C# 6.0 中自动实现的属性也支持不带 set 访问器的用法:

Auto-properties must have a get accessor and can optionally have a set accessor.

…If the auto-property has no set accessor, the backing field is considered readonly (Readonly fields).

https://docs.microsoft.com/en...

从中也可见 private set 和只有 get 还是不完全一样的:

Just like a readonly field, a getter-only auto-property can also be assigned to in the body of a constructor of the enclosing class. Such an assignment assigns directly to the readonly backing field of the property.

Getter-only 的属性只能在构造函数中被赋值,而 private set 的属性还可以在该类的其他方法中被赋值。

关于 C# 6 的更多新特性,参见 https://github.com/dotnet/ros...

A.Template.get' must declare a body because it is not marked abstract or extern. Automatically implemented properties must define both get and set accessors.

报错信息说的很明显呀,可能你是采用自动构造器生成了get和set,然后只写了一个,把另一个删掉了。要么,你就自己写getXX()方法,要么采用自动构造器,不要删去set,自动构造器已经为属性添加了get和set,顺便你最好把你的get贴出来看看,可能get方法写的也有点问题

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进