【问题标题】:Calling this and base constructor?调用 this 和基本构造函数?
【发布时间】:2014-03-28 03:55:48
【问题描述】:

我有一个非常简单直接的问题。 调用类的另一个构造函数以及该类的基本构造函数的标准化方法或正确方法是什么? 我知道第二个示例不起作用。以第三种方式来做这件事似乎有点骇人听闻。那么设计 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;
    }
}

【问题讨论】:

  • dna 是在哪里定义的?
  • 已编辑,不是问题的重点。

标签: c# inheritance constructor


【解决方案1】:

您不能使用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);
        }
    }

【讨论】:

  • 这个问题是编译器无法识别带有可选参数的方法/构造函数与没有可选参数的方法具有相同的签名,因此如果您尝试覆盖非可选参数方法/构造函数它不会工作。
  • 不确定您的意思?我已经用单元测试更新了我的答案,该测试显示工程师 ctor 设置了问题的名称和数量,并将名称设置链接到父 ctor。
  • 假设您没有编写 person 类,并且它不使用 name 作为可选参数,而是使用必需参数。现在在工程师中,您想要创建一个新的构造函数,该构造函数也采用名称,而是作为可选参数。在这种情况下,对 base(name) 的调用不会将所需的基类参数识别为与工程师中的参数具有相同的签名。
  • 对不起,我还是不明白你的意思。更改为 Person(string name) 不会破坏该代码。派生类的 ctor 签名不必与基类匹配。有代码示例吗?
猜你喜欢
  • 1970-01-01
  • 2019-02-01
  • 2011-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-08
  • 2011-07-12
相关资源
最近更新 更多