简体   繁体   English

通用委托方差编译错误

[英]Generic delegate contravariance compilation error

I'm using the MSDN examples for variance in delegate . 我正在使用MSDN示例variance in delegate But the following code is giving me a compilation error. 但是下面的代码给了我一个编译错误。 Based on my understanding, it should accept the First as an argument. 根据我的理解,它应该接受“ First作为论点。 What am I doing wrong? 我究竟做错了什么? The code sample. 代码示例。

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(); 
}    

Errors 错误

Delegate 'ConsoleApplication1.SampleGenericDelegate<ConsoleApplication1.Second,
ConsoleApplication1.First>' has some invalid arguments

Argument 1: cannot convert from 'ConsoleApplication1.First' to    
'ConsoleApplication1.Second'    

secdel has an argument type of Second , so you need to pass an instance of that: secdel的参数类型为Second ,因此您需要传递该实例的实例:

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

The first type in the generic definition is the type used for defining the parameter of the delegate, not the return type. 通用定义中的第一种类型是用于定义委托参数的类型,而不是返回类型。 Change your code as such and you should be good. 这样更改您的代码,您应该会很好。

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(); 
}    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM