我使用variance in delegate
的{{3}}示例。但是下面的代码给了我一个编译错误。根据我的理解,它应该接受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'
答案 0 :(得分:2)
secdel
的参数类型为Second
,因此您需要传递一个实例:
SampleGenericDelegate<Second, First> secdel = AFirstRSecond;
secdel(new Second());
答案 1 :(得分:0)
泛型定义中的第一种类型是用于定义委托参数的类型,而不是返回类型。改变你的代码,你应该做得很好。
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();
}