如何简化多个构造函数? [英] How to simplify multiple constructors?

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

问题描述

我想为一个类提供两个构造函数,如下所示:

I would like to have two constructors for a class, as follows:

public MyClass()
{
    // do stuff here
}

public MyClass(int num)
{
    MyClass();
    // do other stuff here
}

以上是实现我的目的的正确方法吗?有某种更好的速记吗?

Is the above the correct way to achieve my purpose? Is there some kind of shorthand which is better?

推荐答案

public MyClass()
{
    // do stuff
}

public MyClass(int num)
    : this ()
{
    // do other stuff with num
}

:this()位称为构造函数初始化器.C#中的每个构造函数都有一个初始化程序,该初始化程序在构造函数本身的主体之前运行.默认情况下,初始化程序是基类的无参数构造函数(如果该类不是从另一个类显式派生的,则为 Object ).这样可以确保在构造派生类的其余部分之前,正确初始化基类的成员.

The : this() bit is called a Constructor Initialiser. Every constructor in C# has a an initialiser which runs before the body of the constructor itself. By default the initialiser is the parameterless constructor of the base class (or Object if the class is not explicitly derived from another class). This ensures that the members of a base class get initilised correctly before the rest of the derived class is constructed.

每个构造函数的默认构造函数初始化程序可以两种方式覆盖.

The default constructor initialiser for each constructor can be overridden in two ways.

  1. :this(...)构造在同一类中指定另一个构造函数,将其作为应用该构造函数的发起者.
  2. :base(...)构造在基类中指定一个构造函数(通常不是无参数构造函数,因为无论如何这都是默认值).
  1. The : this(...) construct specifies another constructor in the same class to be the initiliser for the constructor that it is applied to.
  2. The : base(...) construct specifies a constructor in the base class (usually not the parameterless constructor, as this is the default anyway).

有关超出预期范围的详细信息,请参见C#4.0语言规范的第10.11节.

For more details than you probably want see the C# 4.0 language specification section 10.11.

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

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