我正在从书本上独自学习C#,不明白我在做什么错。我有一个基本的抽象类Employee
,该类从Director
继承,而类Partner
从其继承。我想基于带有职务的枚举类型在Partner
类中设置职务。假定以下(MWE)代码:
public abstract class Employee
{
protected string title = "Employee"; // underlying field
public string Title { get { return title; } } // read-only property
public Employee() { // do some stuff all children need } // constructor
public virtual void Display()
{
Console.WriteLine("Title: {0}", Title);
}
}
public class Director : Employee
{
protected new string title = "Director"; // shadowing field works here
public int NumberOfProjectsManaged { get; set; } // additional property
public Director() : base() { NumberOfProjectsManaged = 0; } // constructor
public override void Display()
{
base.Display();
Console.WriteLine("Number of Projects Managed: {0}", NumberOfProjectsManaged);
}
}
public class Partner : Director
{
// there are more than two in the actual code, but this is a MWE
public enum SpecificTitle
{
Principal,
Partner
};
public Partner() : base()
{
this._setTitle(SpecificTitle.Partner); // defaults to Partner
}
public Partner(SpecificTitle jobTitle)
{
this._setTitle(jobTitle); // overloaded ctor allows user to specify
}
private void _setTitle(SpecificTitle jobTitle)
{
switch (jobTitle)
{
case SpecificTitle.Principal:
this.title = "Principal";
break;
case SpecificTitle.Partner:
default:
this.title = "Partner";
break;
}
}
}
Director
类工作正常,并且标题始终是所需的“导演”。但是,Partner
类始终具有标题“ Employee”,而不是“ Partner”或“ Principal”。我是否只使用默认构造函数都没关系:Partner DefaultTitle = new Partner(); // title = "Employee"
或者,如果我指定一个:
Partner PrincipalTitle = new Partner(Partner.SpecificTitle.Principal);
要输出值,我使用继承的
Display()
方法:DefaultTitle.Display();
请帮助我了解我在做什么错。
最佳答案
问题是您使用以下行:
protected new string title = "Director";
new
关键字隐藏了Employee
的title
定义。如果那正是您想要的,那不是一个真正的问题。当您调用
Partner.Display
时,就会出现问题,执行路径可追溯到该方法的Employee
定义。在Employee
定义中,哪个使用隐藏的title
字段。在
title
类中设置Partner
时,仅在new
类中设置title
Director
字段,而不在基类Employee
的title
字段中设置。要解决此问题,请删除上述有问题的行。然后,您将要使您的
Director
构造函数看起来像这样。public Director() : base()
{
NumberOfProjectsManaged = 0;
title = "Director";
}
关于c# - 如何将枚举值作为参数传递,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37848762/