1

看着这段代码

delegate void StringAction (string s);
class Test
{
static void Main()
{
    StringAction sa = new StringAction (ActOnObject);
    sa ("hello");
}
static void ActOnObject (object o)
{

   Console.WriteLine (o); // hello
 }
}

由于逆变性,此代码是否有效?( MoreDerivedRef <== LessDerivedRef )

或者因为

与逆变无关) - 在 c# 中,我可以执行类似的ActOnObject (object o)方法ActOnObject ("lalala")

4

2 回答 2

3

此代码有效,因为正如 Eric Lippert 在本文中所说:

方法组到委托转换的参数类型是逆变的。

以上仅对引用类型有效,但stringobject都是引用类型,所以满足要求。

从 C# 2.0 开始就支持这种差异,您不需要版本 4 中引入的额外支持来依赖它。

于 2012-10-01T10:17:37.783 回答
0

是的,这是由于逆变。

This means that you can assign to delegates not only methods that have matching signatures, but also methods that return more derived types (covariance) or that accept parameters that have less derived types (contravariance) than that specified by the delegate type.

Taken from http://msdn.microsoft.com/en-us/library/dd233060(VS.100).aspx

于 2012-10-01T10:32:48.400 回答