简体   繁体   English

使用泛型的乐趣:没有隐式引用转换错误

[英]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的类型参数传递,但约束意味着必须有从TUIE<string>的引用转换,因为Tstring

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM