以下代码导致编译器错误,我认为这不是必要的。有好的解决方法吗?
error CS0704: A nested type cannot be specified through a type parameter `T'
public class Base<T>
{
public T genericData;
public Nested data;
public class Nested
{
}
public static B Create<B>() where B : Base<T>, new() {
var result = new B();
result.data = default(B.Nested);
return result;
}
}
最佳答案
嗯,完整的名字Nested
实际上是 Base<T>.Nested
, 没有其他的。 Nested
-class 因此属于 Base<T>
-class 但不是它的子类。因此,改为编写以下内容:
result.data = default(Base<T>.Nested);
然而 Base<T>
-qualifier 是多余的,因为该类中的代码已经了。所以你也可以只使用这个:
result.data = default(Nested);
除此之外,您还可以使用 result.Data = null
, 作为 Base<T>
是引用类型,默认为 null
.
关于c# - 您可以在 C# 中实例化泛型类型参数的嵌套类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48224266/