C#需要构造函数语法解释 [英] C# Constructor syntax explanation needed
问题描述
有人可以向我解释下面的构造函数语法。我以前没有遇到它,并在同事的代码中注意到。
public Service():this(Service.DoStuff(),DoMoreStuff())
{}
它链接到同一类中的另一个构造函数。基本上任何构造函数都可以使用:this(...)
,或链接到同一类中的另一个构造函数,到基本类中使用:base(...)
的构造函数。如果你没有,它相当于:base()
。
链接的构造函数被执行<
之前 实例变量初始值设定项已经执行。 http://pobox.com/~skeet/csharp/constructors.html\"> my article on constructor chaining or the例如,考虑下面的代码:
使用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
{
//链接到1参数构造函数
public DerivedClass():这个(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 ();
}
}
主
方法调用 DerivedClass
中的无参参数构造函数。它链接到 DerivedClass
中的单参数构造函数,然后它链接到 BaseClass
中的双参数构造函数。当该基础构造函数完成时, DerivedClass
中的单参数构造函数继续,然后当完成时,原始的无参构造函数继续。所以输出是:
基类构造函数
x = Foo,y = 3
派生类无参数
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())
{ }
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
这篇关于C#需要构造函数语法解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!