c# - 对象初始化不尊重传递的属性值
问题描述
下面的代码仅用于测试,它将自动属性设置与属性设置的“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
}
}
解决方案
那是因为你没有对构造函数中指定的参数做任何事情:
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
};
推荐阅读
- amazon-web-services - 在 AWS EC2 实例中使用 S3 的 AccessDenied 应用程序
- javascript - 在我的 NextJS API 路由中解析响应数据时遇到问题,一直返回 undefined
- html - 数字标牌 Websocket 控制
- podman - Podman - 如何使用 Podman 3.0 维护秘密
- swift - 为什么是 UIImage?这里没有?
- python - 是否有 python 函数来获取 json 数据的组合?
- amazon-web-services - 使用无服务器框架部署时,从 Codebuild 构建规范的第一行中删除了新行
- unit-testing - 有没有办法在给定的时间后使单元/集成测试失败?
- angular - 我想在我的角度应用程序中有一个带有标签的子菜单
- java - 如何在滚动期间停止更改回收站视图中的项目数据