简体   繁体   中英

In C#, what is the best/accepted way of doing constructor chaining?

Given the following class:

public class MyClass
{
    private string _param;

    public MyClass ()
    {
        _param = string.Empty;
    }

    public MyClass (string param)
    {
        _param = param;
    }
}

I am torn apart between two ways to chain those constructors:

The first one :

public MyClass () : this (string.Empty)
{
}

public MyClass (string param)
{
    _param = param;
}

The second one:

public MyClass ()
{
    _param = string.Empty;
}

public MyClass (string param) : this ()
{
    _param = param;
}

So, is it better to chain from the parameterless constructor or the other way around?

With your example, I'd go the first way. The second doesn't actually eliminate any code duplication that you are presumably trying to avoid, since you still have to explicitly set _param . The empty this() call in the second approach is completely gratuitous.

I prefer the first. The behavior of the constructors will always be coherent and predictable that way, plus it reduces code duplication.

Chain from pramater less to pramater,

so calling from lessor param constructors with default vals to more parameters

public MyClass()
{
    MyClass(default value here);
}

public Myclass(value)
{
    _value = value;
}

我想从链接从小到大总是更好,即为什么在构造函数中分配一个空字符串然后给定一个字符串,当更有意义的是将默认值(string.Empty)传递给参数化构造函数。

I prefer the first as well. Just as in a complex derived class inheriting from a simple base class, you want the "complex" constructor to build on the functionality of the "basic" one.

Second example in your case really does not make sense, since you duplicate assignment of the class member (if you use MyClass (string param) constructor).

Second approach is more useful if chained constructors are "adding functionality".

Example:

public MyClass ()
{
    _param0 = string.Empty;
}

public MyClass (string param1) : this ()
{
    _param1 = param1;
}

public MyClass (string param1, string param2) : this (param1)
{
    _param2 = param2;
}

In your particular case, the first example is obviously much more appropriate, since you have only one assignment to the same member.

If you state your goal here as "providing a default when no value is specified", then you should clearly use the first approach.

The general rule would then be: chain from least-specific constructor to most-specific.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM