首页 > 解决方案 > 对象初始化不尊重传递的属性值

问题描述

下面的代码仅用于测试,它将自动属性设置与属性设置的“palin old method”混合在一起。

我注意到在调用初始化时创建实例 p1 没有正确设置 Status 属性的值(它显示为零)。但是,正如预期的那样,在初始化语句之外设置属性可以正常工作。

我的问题是为什么下面的语句未能设置 Status 属性?

Person p1 = new Person("71" ,"Sue", Person.ACTIVE_STATUS);

完整的代码是:

public class Program {
 public static void Main()
 {
     Person p1 = new Person("71" ,"Sue", Person.ACTIVE_STATUS);
     Console.WriteLine("Id={0}, Name={1}, Status={2}",p1.Id,p1.Name,p1.Status);
     //from the above, here the status=0    -----(A)
     p1.Status=Person.ACTIVE_STATUS;
     //here status is = 1111                -----(B)
     Console.WriteLine(p1.Status); 
 }
public class Person {
 public const int ACTIVE_STATUS = 111;
 public const int INACTIVE_STATUS = -2;
 private string _id;
 private string _name;

 public Person(String Id, String Name, int Status) 
 {
  this._id = Id;
  this._name = Name;
 }
 public string Id        {get {return this._id;}} 
 public string Name      {get {return this._name;} set {_name=value;} }
 public int Status       {get; set;} //Auto property
}
}

标签: c#

解决方案


那是因为你没有对构造函数中指定的参数做任何事情:

 public Person(String Id, String Name, int Status) 
 {
  this._id = Id;
  this._name = Name;
 }

将其更改为:

 public Person(String Id, String Name, int status) 
 {
  this._id = Id;
  this._name = Name;
  Status = status;
 }

除了将值传递给构造函数,您还可以直接使用公共设置器分配属性,例如:

Person p1 = new Person("71" ,"Sue", Person.ACTIVE_STATUS);
p1.Status = Person.ACTIVE_STATUS;

或者您可以使用对象初始化程序:

Person p1 = new Person("71" ,"Sue", Person.ACTIVE_STATUS)
{
   Status = Person.ACTIVE_STATUS
};

推荐阅读