有没有办法将"this"传递给基础构造函数?
abstract class Base<TSelf>
{
public ICollection<TSelf> List;
public Base(ICollection<TSelf> list, TSelf self)
{
List = list;
List.Add(self);
}
}
class Implementation : Base<Implementation>
{
public Implementation() : base(new List<Implementation>(), this)
{
}
}
Run Code Online (Sandbox Code Playgroud)
显然Implementation,this传递到的构造函数中存在编译错误base.
我也没有看到任何方式list在Base级别实例化.
不,您不能this在构造函数初始化程序中使用.你必须在Add(this)之后添加调用- 但是你可以在Base<TSelf>构造函数中执行此操作,只要你强制转换为TSelf.不幸的是,你需要在转换之前转换this为object第一个,TSelf因为相当复杂的原因围绕类型参数允许的转换.
您可以List<TSelf>在Base构造函数中创建一个,没有问题.这是示例代码,显示了以下两个:
abstract class Base<TSelf>
{
// Let's make it a property rather than a public field...
public ICollection<TSelf> List { get; }
public Base()
{
List = new List<TSelf>();
// This will obviously fail if you try to create a `Base<Foo>`
// from a class that isn't a Foo
TSelf selfThis = (TSelf) (object) this;
List.Add(selfThis);
}
}
class Implementation : Base<Implementation>
{
}
Run Code Online (Sandbox Code Playgroud)
您可以添加约束以TSelf使铸造失败不太可能意外但不是不可能:
abstract class Base<TSelf> where TSelf : Base<TSelf>
Run Code Online (Sandbox Code Playgroud)
这并不能阻止你写作
class Implementation : Base<Implementation> {}
class Evil : Base<Implementation> {}
Run Code Online (Sandbox Code Playgroud)
然后当你构造一个实例时Evil,你试图添加一个无法正常工作的Evil引用List<Implementation>......并且演员无法阻止你走得那么远.