相关疑难解决方法(0)

为什么这个泛型场景会导致TypeLoadException?

这有点啰嗦,所以这是快速版本:

为什么这会导致运行时TypeLoadException?(并且编译器是否应该阻止我这样做?)

interface I
{
    void Foo<T>();
}

class C<T1>
{
    public void Foo<T2>() where T2 : T1 { }
}

class D : C<System.Object>, I { } 
Run Code Online (Sandbox Code Playgroud)

如果您尝试实例化D,则会发生异常.


更长,更具探索性的版本:

考虑:

interface I
{
    void Foo<T>();
}

class C<T1>
{
    public void Foo<T2>() where T2 : T1 { }
}

class some_other_class { }

class D : C<some_other_class>, I { } // compiler error CS0425
Run Code Online (Sandbox Code Playgroud)

这是非法的,因为类型约束C.Foo()与那些不匹配I.Foo().它会生成编译器错误CS0425.

但我想我可能会违反规则:

class D : C<System.Object>, I { } // …
Run Code Online (Sandbox Code Playgroud)

c# generics clr runtime compiler-bug

18
推荐指数
1
解决办法
2345
查看次数

标签 统计

c# ×1

clr ×1

compiler-bug ×1

generics ×1

runtime ×1