我在某堂课上有公共财产.我想要此属性的默认值-1,而没有_MyField之类的私有变量(因为此类中的属性太多,因此我不会一一添加它们).
I have a public property in some class. I want a default value -1 for this property without an private variable like _MyField(because too many properties in this class, i won't add them one by one).
public int MyProperty { get; set; }我认为
[DefaultValueAttribute]无法解决此问题.有任何想法吗?谢谢.
[DefaultValueAttribute] is not working for this issue i think. Any ideas? Thanks.
更新@ 2015年8月现在我们有了C#6!
UPDATE @ Aug 2015 Now we have C# 6!
public int MyProperty { get; set; } = 100; public string EasyToUse { get; } = "YES!"; 推荐答案您基本上有两个选择-您可以在对象的构造函数中设置属性,也可以使用私有字段.
You basically have two options - you can set the property in the constructor of the object, or use a private field.
我个人认为,构造函数是最好的选择,因为人们很容易阅读您的代码,对于类的新实例您的意图是什么.
Personally, I feel the constructor is the best option, as it's clear to people reading your code what your intentions are for a fresh instance of your class.
[DefaultValue] 是用于可视设计器功能的属性,对您的类逻辑没有影响.
[DefaultValue] is an attribute meant for use with visual designer functionality, and has no effect on your class logic.
更多推荐
公共属性的默认值
发布评论