gpt4 book ai didi

c# - 传递给 C# 中的属性时对象变为空

转载 作者:太空狗 更新时间:2023-10-30 00:09:16 25 4
gpt4 key购买 nike

我有一个抽象类 Employee 和其他 2 个扩展它的类(开发人员和经理)。我的问题是每当我创建一个管理器时

Employee man = new Manager(1234567, 30, "Bob", "Pie")

并尝试将其设置在新开发人员的经理字段中,

Employee codemonkey = new Developer(1234568, 20, "Code", "Monkey", (Manager)man)

我不断收到我的 Manager 为空的 ArgumentException。我做了一些检查,当我尝试使用构造函数中的 Manager 属性设置它时,它以某种方式变为 null。任何关于为什么我会收到此错误的建议将不胜感激。 TIA!

每个的代码如下:

//员工类

public abstract class Employee
{
string firstName, lastName;
int id, yearsEmployed;

//Names must be non-empty
public string FirstName
{
get { return firstName; }
set
{
if (!value.Equals(""))
{
firstName = value;
}
else
throw new ArgumentException("name cannot be empty");
}
}
public string LastName
{
get { return lastName; }
set
{
if (!value.Equals(""))
{
lastName = value;
}
else
throw new ArgumentException("name cannot be empty");
}
}
// IDs must be strings consisting of exactly seven digits.
public int ID
{
get { return id; }
set
{
if (value.ToString().Length == 7)
{
id = value;
}
else
throw new ArgumentException("ID must consist of 7 digits");
}
}
// Years employed must always be non-negative.
public int YearsEmployed
{
get { return yearsEmployed; }
set
{
if (value >= 0)
{
yearsEmployed = value;
}
else
throw new ArgumentException("Year employed must be non-negative");
}
}
//Constructor
public Employee(int id, int yearsEmployed,
string firstName, string lastName)
{
this.FirstName = firstName;
this.LastName = lastName;
this.ID = id;
this.YearsEmployed = yearsEmployed;
}
public abstract int GetLevel { get; }
public abstract string GetTitle { get; }
public string GetFullTitle { get { return GetTitle + " " + GetLevel; } }
}

//开发者类:

 public class Developer : Employee
{
Manager manager;

//Manager cannot be null
public Manager Manager
{
get { return manager; }
set
{
if (manager != null)
{
manager = value;
}
else
throw new ArgumentException("Manager cannot be null");
}
}

//Constructor
public Developer(int id, int yearsEmployed, string firstName,
string lastName, Manager manager)
: base(id, yearsEmployed, firstName, lastName)
{
Console.WriteLine("manager is not null:" + manager != null); //True here
this.Manager = manager; // manager is null here
}

public override int GetLevel
{
get { return (this.YearsEmployed + 1) / 3; }
}

public override string GetTitle
{
get { return "Developer"; }
}
}

//经理类

public class Manager : Employee
{
//Constructor
public Manager(int id, int yearsEmployed,
string firstName, string lastName)
: base(id, yearsEmployed, firstName, lastName) { }

public override int GetLevel
{
get { return (YearsEmployed + 1) / 2; }
}

public override string GetTitle
{
get { return "Manager"; }
}
}

最佳答案

你是不是想说:

if (value != null)

代替

if (manager != null)

经理字段将被初始化为空。 value 关键字表示传递给属性的数据。

关于c# - 传递给 C# 中的属性时对象变为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2133917/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com