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? (and why)
Doing:
private int _id = -1
Or
Setting _id = -1 and name = String.Empty in the constructor?
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.
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.
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. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.