Calling this and base constructor?

落花浮王杯 提交于 2021-02-05 11:22:26

问题


I have a pretty simple and straightforward question. What is the standardized way, or the right way, of calling another constructor of a class, along with the base constructor of such class? I understand that the second example does not work. It just seems hackish to be doing it the third way. So what is the way that the people who designed C# expected users to do this?

For example:

public class Person
{
    private int _id;

    private string _name;

    public Person()
    {
        _id = 0;
    }

    public Person(string name)
    {
        _name = name;
    }
}

// Example 1
public class Engineer : Person
{
    private int _numOfProblems;

    public Engineer() : base()
    {
        _numOfProblems = 0;
    }

    public Engineer(string name) : this(), base(name)
    {
    }
}

// Example 2
public class Engineer : Person
{
    private int _numOfProblems;

    public Engineer() : base()
    {
        InitializeEngineer();
    }

    public Engineer(string name) : base(name)
    {
        InitializeEngineer();
    }

    private void InitializeEngineer()
    {
        _numOfProblems = 0;
    }
}

回答1:


Can't you simplify your approach by using an optional parameter?

    public class Person
    {
        public int Id { get; protected set; }
        public string Name { get; protected set; }
        public Person(string name = "")
        {
            Id = 8;
            Name = name;
        }
    }

    public class Engineer : Person
    {
        public int Problems { get; private set; }
        public Engineer(string name = "")
            : base(name)
        {
            Problems = 88;
        }
    }

    [TestFixture]
    public class EngineerFixture
    {
        [Test]
        public void Ctor_SetsProperties_AsSpecified()
        {
            var e = new Engineer("bogus");
            Assert.AreEqual("bogus", e.Name);
            Assert.AreEqual(88, e.Problems);
            Assert.AreEqual(8, e.Id);
        }
    }


来源:https://stackoverflow.com/questions/22703897/calling-this-and-base-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!