c# - 如何同时调用此构造函数和基本构造函数

标签 c# constructor

我如何调用它和基本构造函数?可以打电话吗?

我想要制作的代码是这个

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?

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

为了实现您在示例中尝试执行的操作,您必须像这样重构它。

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

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

<强> Using Constructors (C# Programming Guide)

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.

关于c# - 如何同时调用此构造函数和基本构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41435204/

相关文章:

C# 代码。适用于 win xp 不适用于 win 7

c# - 我该如何解决 "The query results cannot be enumerated more than once"?

c# - 不明确的构造函数调用错误

c++ - 我可以在不分配内存或复制数据的情况下构造一个对象吗?

c# - 为什么在继承中调用固定数据类型参数的对象类参数方法linseed

c# - 捕捉事件窗口开关(也在同一个应用程序中,例如 Chrome 标签)

c# - VSTO Word 激活功能区选项卡

java - 如何在一个 java 构造函数中调用 this() 和 super(sth)?

java - 这个和类名的区别

Javascript 构造函数创建与先前创建的对象具有相同值的新对象