如果我写这段代码:
public class A<T>
{
public class B<T1> : A<T1>
{
public static implicit operator bool(B<T1> b) => true;
}
}
但是如果我分开上课,我不会出错:
public class A<T> { }
public class B<T> : A<T>
{
public static implicit operator bool(B<T> b) => true;
}
这是一个很好的问题。我发现您可以通过指定A<T>.B<T1>
:
public static implicit operator bool(A<T>.B<T1> b) => true;
因此,我开始怀疑为什么在这种特定情况下您需要限定内部类的资格,因为通常您不需要。
本质上,您编写的是一个隐式转换,它可以接受除封闭类型以外的其他类型。请注意,A<int>.B<string>
和A<string>.B<string>
是不同的类。
让我们使用常规方法而不是隐式转换来更清楚地说明正在发生的事情。
public class A<T>
{
public class B<T1>
{
public static void F(B<T1> i) {}
}
}
注意,没有继承子句。现在忍受我。这里的B<T1>
实际上是指A<T>.B<T1>
。这意味着我们不能做这样的事情:
A<int>.B<string>.F(new A<string>.B<string>()); // cannot convert type ...
所以看起来在转换中只写B<T1>
就可以了。但是,当您引入继承子句时...
public class A<T>
{
public class B<T1>: A<T1>
{
public static void F(B<T1> i) {}
}
}
A<int>.B<string>.F(new A<string>.B<string>()); // suddenly this compiles
这意味着您现在可以将A<T>.B<T1>
以外的其他内容传递给隐式转换,并且不允许这样做。