C# Constructor syntax explanation needed

痴心易碎 提交于 2019-12-31 01:45:11

问题


Can someone please explain the following constructor syntax to me. I haven't come across it before and noticed it in a colleagues code.

public Service () : this (Service.DoStuff(), DoMoreStuff())
{ }

回答1:


It chains to another constructor in the same class. Basically any constructor can either chain to another constructor in the same class using : this (...), or to a constructor in the base class using : base(...). If you don't have either, it's equivalent to : base().

The chained constructor is executed after instance variable initializers have been executed, but before the body of the constructor.

See my article on constructor chaining or the MSDN topic on C# constructors for more information.

As an example, consider this code:

using System;

public class BaseClass
{
    public BaseClass(string x, int y)
    {
        Console.WriteLine("Base class constructor");
        Console.WriteLine("x={0}, y={1}", x, y);
    }
}

public class DerivedClass : BaseClass
{
    // Chains to the 1-parameter constructor
    public DerivedClass() : this("Foo")
    {
        Console.WriteLine("Derived class parameterless");
    }

    public DerivedClass(string text) : base(text, text.Length)
    {
        Console.WriteLine("Derived class with parameter");
    }

}

static class Test
{
    static void Main()
    {
        new DerivedClass();
    } 
}

The Main method calls the parameterless constructor in DerivedClass. That chains to the one-parameter constructor in DerivedClass, which then chains to the two-parameter constructor in BaseClass. When that base constructor completes, the one-parameter constructor in DerivedClass continues, then when that finishes, the original parameterless constructor continues. So the output is:

Base class constructor
x=Foo, y=3
Derived class with parameter
Derived class parameterless



回答2:


In this case, there must a a second constructor which will accept two parameters - the return values of Service.DoStuff() and DoMoreStuff(). These two methods must be static methods.



来源:https://stackoverflow.com/questions/12036776/c-sharp-constructor-syntax-explanation-needed

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