这是自动属性的正确语法吗?

发布于 2024-07-29 01:10:59 字数 192 浏览 2 评论 0原文

我已经编程了很长时间,有时很难跟上语言的变化...

之后设置这样的属性真的可以吗

    public string LocaleName
    {
        get;
        set;
    }

在 .net v2不需要内部字段 ? 看来编译器最近处理了这个问题?

I've been programming for so long its hard to keep up with language changes sometimes...

Is it really ok to set properties like this after .net v2

    public string LocaleName
    {
        get;
        set;
    }

Not requiring an inner field? Seems like the compiler takes care of this lately?

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

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

发布评论

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

评论(6

左岸枫 2024-08-05 01:10:59

是的,这是 C# 3.0 中的新功能

Yes, this is a new feature in C# 3.0

如歌彻婉言 2024-08-05 01:10:59

只要您不需要进行任何检查来查看值是否设置正确就可以了。

您可以查看 C# 规范

It's fine as long as you don't need to do any checking to see if the values are set the right way.

You might take a look at the C# Specification.

违心° 2024-08-05 01:10:59

正如您所知,您还可以执行以下操作:

public string MyString
{
   get;
   private set;
}

这为您提供了一个公共访问器和一个私有设置器。

Just so you know, you can also do something like this:

public string MyString
{
   get;
   private set;
}

which gives you a public accessor but a private setter.

梦回梦里 2024-08-05 01:10:59

是的,这些称为“自动实现的属性”。 编译器将为您的属性创建一个支持字段。

因为“自动实现的属性”是“C# 编译器技巧”,所以只要您使用 C# 3.0 编译器来编译代码,您就可以在代码中使用它们并以 .NET Framework 2.0 为目标。

Yes, these are called 'auto implemented properties'. Compiler will create a backing field for your property.

Because 'auto implemented properties' are 'C# compiler trick', you can use them in your code and target .NET framework 2.0, as long as you use C# 3.0 compiler to compile your code.

冰火雁神 2024-08-05 01:10:59

是的,它们被称为

Yes, they're called automatic properties, and will generate the backing field behind the scenes.

携君以终年 2024-08-05 01:10:59

是的。 在 C# 3.0 及更高版本中,当属性访问器中不需要附加逻辑时,自动实现的属性使属性声明更加简洁。 它们还使客户端代码能够创建对象。当您声明属性(如以下示例所示)时,编译器会创建一个只能通过属性的 get 和 set 访问器访问的私有匿名支持字段。

Yes. In C# 3.0 and later, auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors. They also enable client code to create objects When you declare a property as shown in the following example, the compiler creates a private, anonymous backing field can only be accessed through the property's get and set accessors.

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