我在 C# 中有一个简单的问题:
我在通用类(Box)中嵌入了一个类(Properties),如下所示:
public class Box<E> where E : Box{
public class Properties {
}
}
如何从外部类引用子类(属性)?我需要与此 java 语句等效的内容:
Shape<?>.Properties prop = new Shape<?>.Properties();
谢谢
你不能这样做。您必须指定E
.
Shape<OneBox>.Properties
那是不同的班级Shape<AnotherBox>.Properties
泛型类声明中包含的每个类型声明都是隐含的泛型类型声明。在编写对嵌套在泛型类型中的类型的引用时,必须命名包含的构造类型,包括其类型参数。
做不到。一个经典的解决方案,如果Properties
不需要E
,是这样的:
public class Box {
// So that it can't be instantiated, or you could make the class abstract
protected Box()
{
}
public class Properties {
}
}
public class Box<E> : Box {
}