这是自动属性的正确语法吗?
我已经编程了很长时间,有时很难跟上语言的变化...
之后设置这样的属性真的可以吗
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
是的,这是 C# 3.0 中的新功能
Yes, this is a new feature in C# 3.0
只要您不需要进行任何检查来查看值是否设置正确就可以了。
您可以查看 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.
正如您所知,您还可以执行以下操作:
这为您提供了一个公共访问器和一个私有设置器。
Just so you know, you can also do something like this:
which gives you a public accessor but a private setter.
是的,这些称为“自动实现的属性”。 编译器将为您的属性创建一个支持字段。
因为“自动实现的属性”是“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.
是的,它们被称为
Yes, they're called automatic properties, and will generate the backing field behind the scenes.
是的。 在 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.