Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 泛型的乐趣:没有隐式引用转换错误_C#_.net_Generics_Resharper - Fatal编程技术网

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

C# 泛型的乐趣:没有隐式引用转换错误,c#,.net,generics,resharper,C#,.net,Generics,Resharper,我测试了这段代码,发现它无法编译 interface IE<T> { } class A<T> : IE<T> { public static void F<TU>() where TU : IE<T> { } static void Foo() { F<A<int>>(); } } 接口IE { } A类:即 { 公共静态无效F(),其中

我测试了这段代码,发现它无法编译

interface IE<T>
{

}

class A<T> : IE<T>
{
    public static void F<TU>() where TU : IE<T>
    {

    }

    static void Foo()
    {
        F<A<int>>();
    }
}
接口IE
{
}
A类:即
{
公共静态无效F(),其中TU:IE
{
}
静态void Foo()
{
F();
}
}
即使我在TU:A的位置添加了
公共静态void F(),它也会失败

根据C#规格,它是有效的。如果我删除containt
where TU:IE
,但在本例中它不会影响,因为
A
IE
的子类型

这也很有趣,因为resharper建议将
IE
接口添加到
A

为什么此代码无效?

不,它无效。约束

where TU : IE<T>
这试图将
A
作为
TU
的类型参数传递,但约束意味着必须有从
TU
IE
的引用转换,因为
T
string

没有从
A
IE
的转换,因此它被破坏了。基本上,你对“
A
IE
的子类型”的期望并不适用于所有
t

现在您可以将其更改为:

public static void F<TU, TT>() where TU : IE<TT>
{
}

static void Foo()
{
    F<A<int>, int>();
}
publicstaticvoidf(),其中TU:IE
{
}
静态void Foo()
{
F();
}
这现在是有效的,因为它根本不涉及
t

public static void F<TU, TT>() where TU : IE<TT>
{
}

static void Foo()
{
    F<A<int>, int>();
}