调用这个和基础构造函数?

时间:2014-03-28 03:55:49

标签: c# inheritance constructor

我有一个非常简单明了的问题。 调用类的另一个构造函数以及此类的基本构造函数的标准化方法或正确方法是什么? 我知道第二个例子不起作用。以第三种方式做这件事似乎很苛刻。那么设计C#的人希望用户做这件事的方式是什么?

例如:

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 个答案:

答案 0 :(得分:3)

您是否可以使用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);
        }
    }