Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/259.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# 从派生类中创建的闭包调用基类泛型类型约束方法会导致VerificationException_C#_Generics_Inheritance_Closures - Fatal编程技术网

C# 从派生类中创建的闭包调用基类泛型类型约束方法会导致VerificationException

C# 从派生类中创建的闭包调用基类泛型类型约束方法会导致VerificationException,c#,generics,inheritance,closures,C#,Generics,Inheritance,Closures,我有一个基类,实现了一个接口,它被大大简化,如下所示: interface I { void DoStuff<T>(T t) where T : class; } class A : I { public virtual void DoStuff<T>(T t) where T : class { // do some work System.Console.WriteLine(t); } } 这会在运行

我有一个基类,实现了一个接口,它被大大简化,如下所示:

interface I
{
    void DoStuff<T>(T t) where T : class;
}

class A : I
{
    public virtual void DoStuff<T>(T t) where T : class
    {
        // do some work
        System.Console.WriteLine(t);
    }
}
这会在运行时抛出一个带有消息方法约束的VerificationException。a.DoStuff:类型参数“T”违反了类型参数“T”的约束

这个问题可以通过以下两种方法解决 *生成闭包=>{new A.DoStufft;} *创建方法B.BaseDoStuffT t,其中t:class{base.DoStufft;}


我已经用第二种方法解决了这个问题,但我真的很好奇为什么这不起作用。有什么想法吗?

A在代码中没有发现任何问题。你能分享.NET版本吗?VS2010/.NET 4.0适用于我。您在使用什么?VS2012/.Net4.5存在相同的运行时问题。。。答案就在这里:我看不出直接从派生类调用base.DoStufft与在闭包中调用它有什么不同。
class B : A
{
    public override void DoStuff<T>(T t)
    {
        DoMoreSpecificStuff(() => { base.DoStuff(t); });
    }

    public void DoMoreSpecificStuff(Action action)
    {
        // set some stuff up before calling the action
        action();
        // tear some stuff down
    }
}
I i = new B();
i.DoStuff("Hello World");