[英]Can you instantiate a nested type of a generic type argument in C#?
The following code results in a compiler error that I don't see should be necessary. 以下代码导致编译器错误,我认为不应该是必需的。 Is there a good workaround?
有一个很好的解决方法吗?
error CS0704: A nested type cannot be specified through a type parameter `T'
错误CS0704:无法通过类型参数“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;
}
}
Well, the complete name of Nested
is actually Base<T>.Nested
, nothing else. 好吧,
Nested
的完整名称实际上是Base<T>.Nested
,没有别的。 The Nested
-class thus belongs to the Base<T>
-class but not to its child-classes. Nested
-class因此属于Base<T>
-class而不属于其子类。 Thus write the following instead: 因此,请写下以下内容:
result.data = default(Base<T>.Nested);
However the Base<T>
-qualifier is redundant, as the code already is within that class. 然而,
Base<T>
-qualifier是多余的,因为代码已经是该类中。 So you could also just use this: 所以你也可以使用这个:
result.data = default(Nested);
Apart from this you could also just use result.Data = null
, as Base<T>
is a reference-type, which defaults to null
. 除此之外,您还可以使用
result.Data = null
,因为Base<T>
是一个引用类型,默认为null
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.