c# - 初始化成员变量的最佳实践?

标签 c#

<分区>

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>();在所有这些构造函数中,哈哈。第一种方式有什么问题吗?谢谢

编辑: 我意识到我可以链接构造函数,但这是一个相当复杂的类......一些构造函数调用基类,一些已经调用其他构造函数等等。

最佳答案

您不必初始化成员变量,但这样做也无妨。成员变量自动获取它们的默认值,通常是对象的 null 和基本类型的默认值(例如 0int)。

至于拥有不同的构造函数,您不必在每个版本中重复成员初始化,因为您可以从任何其他版本调用重载构造函数,就像使用重载方法一样。

关于最佳实践,个人我在构造函数中初始化成员变量,因为这是我想将我的对象“构造”到稳定状态的地方。换句话说,即使我在声明它们的地方初始化了成员变量,当构造函数被调用时,也好像我正在把石板擦干净。

关于c# - 初始化成员变量的最佳实践?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1206894/

相关文章:

c# - 如何在 asp :linkButton 上的鼠标悬停事件上显示图像

c# - Asp.NET MVC REST API : How to get Client Host Name

c# - WPF 在 WPF 窗口中打开 exe 程序

c# - 将多维数组从 C# 传递到 C++ DLL

c# - 不同命名空间中的类

C# 反射 : Replace a referenced assembly

c# - XML 序列化类结果为空 XML

c# - 查看asp.net mvc和asp.net core mvc的目录编译时间差异

c# - 如何拥有 DataTemplates 类?

java - 构建对象列表时仅检索某些属性