<分区>
Possible Duplicate:
Best Practice: Initialize class fields in constructor or at declaration?
我正在使用 C#,但这可能适用于 Java(或任何其他允许这种行为的语言)...
哪种方式更可取/最佳实践?假设我总是需要 _memberVar
1.
class MyClass
{
private Dictionary<int, string> _memberVar = new Dictionary<int, string>();
public MyClass() {}
}
- 或 -
2.
class MyClass
{
private Dictionary<int, string> _memberVar = null
public MyClass()
{
_memberVar = new Dictionary<int, string>();
}
}
现在假设 MyClass
有超过 10 个构造函数...所以我不想有 _memberVar = new Dictionary<int, string>();
在所有这些构造函数中,哈哈。第一种方式有什么问题吗?谢谢
编辑: 我意识到我可以链接构造函数,但这是一个相当复杂的类......一些构造函数调用基类,一些已经调用其他构造函数等等。