C# 自动属性——设置默认值
为 C# 公共属性设置默认值的最简单/直接的方法是什么?
// 我如何为此设置默认值?
public string MyProperty { get; set; }
请不要建议我使用私人财产和私人财产。实现获取/设置公共属性。尽量保持简洁,并且不想争论为什么这样更好。谢谢。
What's the easiest/straight-forward way of setting a default value for a C# public property?
// how do I set a default for this?
public string MyProperty { get; set; }
Please don't suggest that I use a private property & implement the get/set public properties. Trying to keep this concise, and don't want to get into an argument about why that's so much better. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
从 C# 6.0 开始,您可以为自动属性分配默认值。
As of C# 6.0 you can assign a default value to an auto-property.
如果要使用属性的自动实现,唯一真正的选择是在构造函数中初始化属性值。
if you're going to use auto-implementation of properties, the only real option is to initialize the property values in the constructor(s).
不,如果您可以标记属性以指示默认值,那就太好了,但您不能。如果您确实想使用自动属性,则无法在属性声明中设置默认值。
我想出的最干净的解决方法是在构造函数中设置默认值。还是有点丑啊。默认值不与属性声明位于同一位置,如果您有多个构造函数,这可能会很痛苦,但这仍然是我发现的最好的
No, it would be nice if you could just mark up the property to indicate the default value, but you can't. If you really want to use automatic properties, you can't set a default in property declaration.
The cleanest workaround I've come up with is to set the defaults in the constructor. It's still a little ugly. Defaults are not colocated with the property declaraion, and it can be a pain if you have multiple constructors, but that's still the best I've found
这是设置此类默认值的标准方法。您可能不喜欢它,但即使是自动属性语法在编译后也会执行的操作 - 它会生成一个私有字段并在 getter 和 setter 中使用它。
您可以在构造函数中设置该属性,该属性将尽可能接近默认值。
That's the standard way to set such defaults. You might not like it, but that what even the automatic properties syntax does after compilation - it generates a private field and uses that in the getter and setter.
You can set the property in a constructor, which will be as close to a default as you can get.
只需在构造函数中初始化它:
请注意,如果您有多个构造函数,则需要确保每个构造函数都设置属性或委托给另一个构造函数。
Just initialize it in the constructor:
Note that if you have multiple constructors, you'll need to make sure that each of them either sets the property or delegates to another constructor which does.
在构造函数中设置默认值:
Set the default in your constructor: