泛型委托逆向编译错误

本文关键字:编译 错误 泛型 | 更新日期: 2023-09-27 18:19:00

我使用的是variance in delegate的MSDN示例。但是下面的代码给了我一个编译错误。根据我的理解,它应该接受First作为一个参数。我做错了什么?代码示例:

SampleGenericDelegate<Second, First> secdel = AFirstRSecond;
secdel(new First()); //compilation error here.
public class First { }
public class Second : First { }
public delegate R SampleGenericDelegate<A, R>(A a);
public static Second AFirstRSecond(First first)
{ 
    return new Second(); 
}    

错误
Delegate 'ConsoleApplication1.SampleGenericDelegate<ConsoleApplication1.Second,
ConsoleApplication1.First>' has some invalid arguments
Argument 1: cannot convert from 'ConsoleApplication1.First' to    
'ConsoleApplication1.Second'    

泛型委托逆向编译错误

secdel有一个参数类型Second,所以你需要传递一个实例:

SampleGenericDelegate<Second, First> secdel = AFirstRSecond;
secdel(new Second());

泛型定义中的第一个类型是用于定义委托的参数的类型,而不是返回类型。这样修改你的代码,你应该是好的。

SampleGenericDelegate<First, Second> secdel = AFirstRSecond;
secdel(new First()); //compilation error here.
public class First { }
public class Second : First { }
public delegate R SampleGenericDelegate<A, R>(A a);
public static Second AFirstRSecond(First first)
{ 
    return new Second(); 
}