[英]Default value of a property
If you have an object like this: 如果您有这样的对象:
public class Foo
{
private int _id;
public int id
{
get { return _id; }
set { _id = value; }
}
private string _name;
public string name
{
get { return _name; }
set { _name = value; }
}
}
And you want to initialize id to -1 and name to String.Empty what is the best practice? 并且您希望将id初始化为-1并将其命名为String.Empty,最佳做法是什么? (and why)
(以及为什么)
Doing: 这样做:
private int _id = -1
Or 要么
Setting _id = -1 and name = String.Empty in the constructor? 在构造函数中设置_id = -1和name = String.Empty?
This is more of a style question than anything else. 这不仅仅是一个风格问题。 There are only a few cases where it is a functional issue
只有少数几个案例是功能性问题
depends on when you want it to be set... 取决于你想要什么时候设置...
private int _id = -1
will initialize _id before the constructor is called. 将在调用构造函数之前初始化_id。
The field approach is concise, which gets a lot of votes, but my preference (for simple properties) would be to use auto-properties, in which case you are forced to use the constructor: 字段方法简洁,获得了大量的投票,但我的偏好(对于简单属性)将使用自动属性,在这种情况下,您被迫使用构造函数:
public Foo() {
Id = -1;
Name = "";
}
public int Id {get;set;}
public string Name {get;set;}
You might also consider using [DefaultValue(-1)]
etc, which helps designers and serializers, but this does not affect the initial value of an auto implemented property (or a regular property) - it is additional info only. 您也可以考虑使用
[DefaultValue(-1)]
等,这有助于设计人员和序列化程序,但这不会影响自动实现的属性(或常规属性)的初始值 - 它只是附加信息。
Setting it "inline" rather than using the constructor seems, to me, to indicate intention better. 对我而言,将其设置为“内联”而不是使用构造函数似乎更能表明意图。 Functionally they're the same.
功能上他们是一样的。
CLR向导可能会纠正我,但我相信这两种方法在功能上是相同的,但您可以提出一个参数,即在构造函数中设置默认值更明确,更明显,但也有点麻烦。
Inline initialization is added to the top of the constructor by the C# compiler so there is really no difference. 内联初始化由C#编译器添加到构造函数的顶部,因此实际上没有区别。 Personally I prefer always adding constructors even if it is only a default constructor.
我个人更喜欢总是添加构造函数,即使它只是一个默认的构造函数。
It's mainly the question of style preference. 这主要是风格偏好的问题。 I usually assign them in the constructor, because it is a sane place for all the data and procedures that take place when object is instantiated.
我通常在构造函数中分配它们,因为它是实例化对象时发生的所有数据和过程的理想位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.