调用this和base构造函数

本文关键字:构造函数 base this 调用 | 更新日期: 2023-09-27 17:54:11

我有一个非常简单直接的问题。调用类的另一个构造函数以及该类的基构造函数的标准化方法或正确方法是什么?我知道第二个例子行不通。只是用第三种方式来做这件事似乎有些粗俗。那么,设计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;
    }
}

调用this和base构造函数

难道不能通过使用可选参数来简化您的方法吗?

    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);
        }
    }