可能重复: C#成员变量初始化;最好的做法?
Possible Duplicate: C# member variable initialization; best practice?
有没有任何好处的:
public class RemotingEngine
{
uint m_currentValueId;
object m_lock;
public RemotingEngine()
{
m_currentValueId = 0;
m_lock = new object();
}
VS。这样的:
vs. this:
public class RemotingEngine
{
uint m_currentValueId = 0;
object m_lock = new object();
我一直回避第二个只是因为感觉脏。这显然是少打字,这样是吸引我。
I have been avoiding the second one just because it feels 'dirty'. It is obviously less typing so that is appealing to me.
它可以使在继承的情况有所不同。查看对象的初始化顺序此链接: http://www.csharp411.com/c-object-initialization/
It can make a difference in an inheritance situation. See this link on the object initialization order: http://www.csharp411.com/c-object-initialization/
派生的静态字段 派生静态构造函数 派生实例字段 在相应的静态字段 在相应的静态构造函数 在相应的实例字段 在相应的实例构造 派生实例构造因此,如果这是一个派生类中,整个基础对象时,你的派生字段被初始化和构造函数之间运行时初始化。
So if this is a derived class, the entire base object is initialized between when your derived field is initialized and when your constructor runs.