我怎么称呼这个和基本构造函数 [英] How do I call both this and base constructor

查看:52
本文介绍了我怎么称呼这个和基本构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该如何称呼它为基本构造函数?可以打电话吗?

How can I call this and base constructor? Is it possible to call?

我要输入的代码是这个

public class ObservableTestCollection<T> : ObservableCollection<T>
{
    public T Parent;   
    public ObservableTestCollection(T parent)
    {
        Parent = parent;
    }
    public ObservableTestCollection(T parent, IEnumerable<T> source): base(source) ,this(parent)
    {

    }
}

推荐答案

该如何称呼它为基本构造函数?可以打电话吗?

How can I call this and base constructor? Is it possible to call?

您不能像示例中那样调用此构造函数和基本构造函数.

You cannot call this and base constructor like in your example.

要实现您在示例中尝试做的事情,您将必须像这样重构它.

To achieve what you are trying to do in your example, you are going to have to refactor it like this.

public class ObservableTestCollection<T> : ObservableCollection<T> {
    public T Parent;   

    //This constructor calls the instance constructor
    public ObservableTestCollection(T parent) : this(parent, Enumerable.Empty<T>()) {

    }

    //Instance constructor is calling the base constructor
    public ObservableTestCollection(T parent, IEnumerable<T> source) : base(source) {
        Parent = parent;
    }
}

第二个构造函数用于填充局部变量并调用基本构造函数.让我们将该构造函数称为 instance构造函数.现在,其他构造函数可以使用 this 关键字来调用实例构造函数.

The second constructor is used to populate local variable and call the base constructor. Lets call that constructor the instance constructor. The instance constructor is now available to be called by other constructors using the this keyword.

使用构造函数(C#编程指南)

Using Constructors (C# Programming Guide)

构造函数可以通过以下方法在同一对象中调用另一个构造函数:使用 this 关键字.像 base 一样, this 可以有或没有参数,以及构造函数中的任何参数都可以作为参数或作为表达式的一部分.

A constructor can invoke another constructor in the same object by using the this keyword. Like base, this can be used with or without parameters, and any parameters in the constructor are available as parameters to this, or as part of an expression.

这篇关于我怎么称呼这个和基本构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆