我如何调用它和基本构造函数?可以打电话吗?
我想要制作的代码是这个
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/