加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

需要C#构造函数语法解释

发布时间:2020-12-16 00:21:07 所属栏目:百科 来源:网络整理
导读:有人可以向我解释以下构造函数语法.我以前没遇到它,并在同事代码中注意到它. public Service () : this (Service.DoStuff(),DoMoreStuff()){ } 解决方法 它链接到同一个类中的另一个构造函数.基本上任何构造函数都可以使用:this(…)链接到同一个类中的另一
有人可以向我解释以下构造函数语法.我以前没遇到它,并在同事代码中注意到它.

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

解决方法

它链接到同一个类中的另一个构造函数.基本上任何构造函数都可以使用:this(…)链接到同一个类中的另一个构造函数,或者使用:base(…)链接到基类中的构造函数.如果你没有,它相当于:base().

链接的构造函数在执行实例变量初始化程序之后但在构造函数的主体之前执行.

有关更多信息,请参见my article on constructor chaining或MSDN topic on C# constructors.

例如,请考虑以下代码:

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();
    } 
}

Main方法在DerivedClass中调用无参数构造函数.它链接到DerivedClass中的单参数构造函数,然后链接到BaseClass中的双参数构造函数.当该基础构造函数完成时,DerivedClass中的单参数构造函数继续,然后当完成时,原始无参数构造函数继续.所以输出是:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读