C#:初始化类变量

标签 c# .net constructor class-design

<分区>

Possible Duplicate:
C# member variable initialization; best practice?

这是初始化类变量的正确方法。 [1] 和 [2] 有什么区别。

//[1]
public class Person
{
   private int mPersonID = 0; 
   private string mPersonName = "";
}

//[2]
public class Person
{
     private int mPersonID = 0; 
     private string mPersonName = "";

     public Person()
     {
         InitializePerson();
     }

     private void InitializePerson()
     {
          mPersonID = 0;
          mPersonName = "";
     }
}

最佳答案

作为声明的一部分被分配默认值的实例变量将在构造函数运行之前立即分配该值,从外部看,1) 和 2) 之间的行为没有明显差异,这主要是一个问题风格。

您还在您的方法 2) 中引入了一个额外的 InitializePerson() 方法 - 如果您有多个构造函数,那么所有构造函数都可以使用相同的通用初始化方法(这使代码保持干爽),这可能是有益的).

根据评论进行编辑,请参阅 MSDN :

Fields are initialized immediately before the constructor for the object instance is called. If the constructor assigns the value of a field, it will overwrite any value given during field declaration.

关于C#:初始化类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6287733/

相关文章:

c# - 无法注册 IRelationalTypeMappingSource

c# - 如何使用 EPPlus 将筛选后的 DataGridView 数据保存到 Excel 中?

c# - 为什么 Environment.CommandLine.Trim ('"') 不删除尾随引号?

c# - 从 C# 使用 C 库的技巧

PHP类在构造函数中分配属性

c# - 使用 XSD 创建 XML 并发布到 URL 的步骤

.net - Ninject 中的 RequestScope() 和 Kernel.Get<>

android - 这种类型有一个构造函数,必须在这里初始化 - Kotlin

java - 初学者 Java 构造函数中不需要参数错误

c# - 反序列化从 Azure 表检索的 DynamicTableEntity