调用这个和基本构造函数? [英] Calling this and base constructor?

查看:32
本文介绍了调用这个和基本构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单明了的问题.调用一个类的另一个构造函数以及该类的基本构造函数的标准化方法或正确方法是什么?我了解第二个示例不起作用.似乎第三种方式做事有点胆小.那么,设计C#的人们期望用户这样做的方式是什么?

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?

例如:

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

推荐答案

不能通过使用

这篇关于调用这个和基本构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆