我如何调用构造函数初始值设定项,base()和this()?

Aar*_*ide 34 c# constructor

这很容易解决,但我只是好奇我是否可以使用语言功能,或者可能是语言不允许这意味着我在课堂设计中犯了一个逻辑错误.

我正在对我的代码进行自我审查,以帮助"强化"它以便重复使用,我刚刚来到:

public partial class TrackTyped : Component
{
    IContainer components = null;

    public TrackTyped()
        : base()
    {
        InitializeComponent();
    }

    public TrackTyped(IContainer container)
        : base()
    {
        container.Add(this);
        InitializeComponent();
    }
}
Run Code Online (Sandbox Code Playgroud)

当我在两个构造函数中看到相同的代码行时,我通常会做的是使用"this()"调用另一个代码,但我似乎无法做到.

如果我正确阅读规范(我刚开始尝试阅读规范,所以我可能不对):

10.11 Instance Constructors
   constructor-declarator:
      identifier   (   formal-parameter-listopt   )   constructor-initializeropt
   constructor-initializer:
      :   base   (   argument-listopt   )
      :   this   (   argument-listopt   )
Run Code Online (Sandbox Code Playgroud)

它说我只能有其中一个.

问题:10.11意味着没有理由需要同时调用它们,还是只是暗示语言只支持调用它?

mar*_*arc 25

不需要同时调用它们,因为this重定向到将调用的另一个构造函数base.


dle*_*lev 10

这似乎是你想要的:

public partial class TrackTyped : Component
{
    IContainer components = null;

    public TrackTyped()
        : base()
    {
        InitializeComponent();
    }

    public TrackTyped(IContainer container)
        : this()
    {
        container.Add(this);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,第二个构造函数中的语句顺序现在不同了.如果这很重要,那么就没有什么好方法可以做你想要的,因为即使你有相同的线,功能也略有不同.在这种情况下,您只需要重复单行.不要出汗.

你正在正确阅读规范:它必须是一个或另一个.


Arm*_*yan 9

你没有,你不能.您可以将构造函数调用转发给同一个类的另一个构造函数:this(...).该链中的最后一个构造函数必须通过隐式或显式初始化基数:base(...)

假设A类有两个构造函数.一个初始化与底座:base(2),另用:base(3).如果允许第一个构造函数也指定:this (/*call the other ctor*/)如何初始化基数:使用2还是3?这就是为什么不允许这些事情的原因


Nit*_*ngh 6

通常在具有多个要通过构造函数初始化的属性的类中完成,其中一些属性是可选的。我们有一个最大的构造函数,它接受所有调用基本构造函数的参数。通过将null /默认值传递给此大构造函数,所有其他构造函数重定向到此构造函数。这样,所有初始化代码都保留在一个地方,可供其他人重复使用。

public MissingEntityException(Type type, string criteria, string message = "") 
    : this(type, criteria, message, null)
{           
}

public MissingEntityException(Type type, string criteria, string message, Exception innerException) 
     : base(message, innerException) 
{
    this.EntityType = type;
    this.Criteria = criteria;
}
Run Code Online (Sandbox Code Playgroud)

这在整个层次结构中均受支持,并且可以涉及任何数量或参数。