为什么自动属性需要 getter 和 setter?

发布于 2024-07-09 09:51:13 字数 232 浏览 5 评论 0原文

在 C# 中,如果我声明一个自动实现的属性,为什么我必须同时声明 get 和 set 部分?

public string ThisWorks { get; set; }

public string ThisDoesnt { get; }

,这不是只是语法糖吗?即编译器为属性插入一个私有字段? 那么为什么会出现这个问题呢?

好奇的。

In C#, if I declare an auto-implemented property, why do I have to declare BOTH the get and set part?

i.e.

public string ThisWorks { get; set; }

public string ThisDoesnt { get; }

Isn't this just syntactic sugar - i.e. the compiler inserts a private field for the property? So why the problem?

Curious.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

小帐篷 2024-07-16 09:51:13

如果您没有设置器 - 那么您将如何设置该属性?

顺便说一句,您可以指定可访问性,例如:

public string Foo
{
  get;
  private set;
}

If you didn't have a setter - then how would you ever set the property?

Incidentally, you can specify the accessibility, eg:

public string Foo
{
  get;
  private set;
}
夜声 2024-07-16 09:51:13

如果没有设置器,您将永远无法提供值 - 因为您没有任何方法来指定支持变量的名称。

我请求了一个只读自动属性,声明如下:

public string ReadonlyProperty { get; readonly set; }

它将创建一个只读支持变量,一个只有 getter 的属性,并将对 setter 的所有调用转换为对变量的直接访问。 您只能在构造函数中调用 setter - 就像普通的只读变量一样。

我们将看看这个请求是否有任何好处......目前它不在那里真是太遗憾了,因为它使得实现不可变类型比实现可变类型更困难:(

Without a setter, you would never be able to provide a value - as you don't have any way of specifying the backing variable's name.

I've requested a readonly automatic property, declared like this:

public string ReadonlyProperty { get; readonly set; }

which would create a readonly backing variable, a property with only a getter, and translate all calls to the setter into direct access to the variable. You could only call the setter within the constructor - just like for normal readonly variables.

We'll see whether this request does any good... it's a real shame it's not in there at the moment, as it makes it harder to implement immutable types than mutable types :(

£冰雨忧蓝° 2024-07-16 09:51:13

自动实现的属性没有可访问的私有存储,因此如果没有设置器,您将无法设置该值,从而使其完全无用。

An auto-implemented property has no accessible private store, so you would have no way to set the value without a setter, making it totally useless.

离不开的别离 2024-07-16 09:51:13

您需要一个集合 - 否则,您的自动实现的属性如何获取其值? 自动实现属性时,您必须有一个 set 访问器,至少在构造过程中为其赋予一个值。

You need a set - otherwise, how does your auto-implemented property get its value? When auto-implementing the property, you have to have a set accessor to at least give it a value during construction.

半仙 2024-07-16 09:51:13

有趣的是,即使项目配置为使用 C# 版本 5,Visual Studio 2015 中的新 Roslyn 编译器现在也允许这样做。

Interestingly, the new Roslyn compiler in Visual Studio 2015 now allows this, even if the project is configured to use C# version 5.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文