How to simplify multiple constructors?

[亡魂溺海] 提交于 2021-02-16 08:35:47

问题


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?


回答1:


public MyClass()
{
    // do stuff
}

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

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. 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).

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




回答2:


The correct syntax looks like this:

public MyClass() 
{ 
    // do stuff here 
} 

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

Note the this() at the second constructor. This calls the constructor in the same class with no parameters.

You could also have it the other way around:

public MyClass() : this(someReasonableDefaultValueForNum)
{ 
} 

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

There is only one more "function" you can use instead of this at this place which is base:

public MyClass(int num) : base(someParameterOnTheBaseClassConstructor)
{
}

This is useful if you don't want to call the default parameterless constructor in the base class but one of the constructors that takes parameters.




回答3:


You can do it like this:

public MyClass()
{
    // do stuff here
}

public MyClass(int num) : this()
{

    // do other stuff here
}



回答4:


Maybe use one constructor with a default value for the parameter:

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



回答5:


You can do the following:

public MyClass()
   : this(1) { }

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


来源:https://stackoverflow.com/questions/12000096/how-to-simplify-multiple-constructors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!