我正在从书本上独自学习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关键字隐藏了Employeetitle定义。

如果那正是您想要的,那不是一个真正的问题。当您调用Partner.Display时,就会出现问题,执行路径可追溯到该方法的Employee定义。在Employee定义中,哪个使用隐藏的title字段。

title类中设置Partner时,仅在new类中设置title Director字段,而不在基类Employeetitle字段中设置。

要解决此问题,请删除上述有问题的行。然后,您将要使您的Director构造函数看起来像这样。

public Director() : base()
{
    NumberOfProjectsManaged = 0;
    title = "Director";
}

关于c# - 如何将枚举值作为参数传递,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37848762/

10-12 06:22