[英]Fun with generics: no implicit reference conversion error
I tested this code and got that it doesn't compiles. 我测试了这段代码并得到了它没有编译。
interface IE<T>
{
}
class A<T> : IE<T>
{
public static void F<TU>() where TU : IE<T>
{
}
static void Foo()
{
F<A<int>>();
}
}
It fails even if I add public static void F<TU>() where TU : A<int>, IE<T>
. 即使我添加
public static void F<TU>() where TU : A<int>, IE<T>
也会失败。
afaik it's valid according to C# specs. afaik根据C#规范有效。 If I remove contraint
where TU : IE<T>
but in this case it couldn't affect, because A<int>
is subtype of IE<T>
. 如果我删除
where TU : IE<T>
约束where TU : IE<T>
但在这种情况下它不会影响,因为A<int>
是IE<T>
子类型。
And it's also funny because resharper suggest to add IE<T>
interface to A
而且它也很有趣,因为resharper建议将
IE<T>
接口添加到A
why this code isn't valid? 为什么这段代码无效?
No, it's not valid. 不,这不是有效的。 The constraint of
的约束
where TU : IE<T>
refers to the current T
, ie the one for the type on which you're calling this method. 指的是当前的
T
,即您调用此方法的类型。
Consider a call of: 考虑一下:
A<string>.Foo();
That's trying to pass A<int>
as a type argument for TU
, but the constraint means that there must be a reference conversion from TU
to IE<string>
, because T
is string
. 那是试图将
A<int>
作为TU
的类型参数传递,但约束意味着必须有从TU
到IE<string>
的引用转换,因为T
是string
。
There's no conversion from A<int>
to IE<string>
, hence it's broken. 没有从
A<int>
到IE<string>
,因此它已被破坏。 Basically your expectation of " A<int>
is subtype of IE<T>
" isn't true for all T
. 基本上你对“
A<int>
是IE<T>
子类型”的期望并非对所有T
。
Now you could change it to: 现在您可以将其更改为:
public static void F<TU, TT>() where TU : IE<TT>
{
}
static void Foo()
{
F<A<int>, int>();
}
That's now valid, because it doesn't involve T
at all. 这现在有效,因为它根本不涉及
T
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.