代表协方差混淆难题! [英] Delegate Covariance Confusion Conundrum!

查看:88
本文介绍了代表协方差混淆难题!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这不起作用?我不能正确理解委托协方差吗?

Why does this not work? Do I not understand delegate covariance correctly?

public delegate void MyDelegate(object obj)

public class MyClass
{
    public MyClass()
    {
         //Error: Expected method with 'void MyDelegate(object)' signature
         _delegate = MyMethod;
    }

    private MyDelegate _delegate;

    public void MyMethod(SomeObject obj)
    {}

}


推荐答案

更正-您不能正确理解协方差-但:)如果您使用相同的类型但与 return相同,则您的代码将正常工作值,如下所示:

Correct - you don't understand covariance correctly - yet :) Your code would work if you had the same types but as return values, like this:

public delegate object MyDelegate()

public class MyClass
{
    public MyClass()
    {
         _delegate = MyMethod;
    }

    private MyDelegate _delegate;

    public SomeObject MyMethod() { return null; }
}

这将证明协方差。或者,可以将其保留为参数,但可以在以下类型之间进行切换:

That would demonstrate covariance. Alternatively, you can keep it as parameters but switch the types around:

public delegate void MyDelegate(SomeObject obj)

public class MyClass
{
    public MyClass()
    {
         _delegate = MyMethod;
    }

    private MyDelegate _delegate;

    public void MyMethod(object obj) {}
}

这现在显示出 contravariance

我的经验法则是问自己:给与会代表,我该怎么办?我可以传入一个会破坏该方法的参数,则转换应该会失败。如果该方法可以返回会破坏调用方的东西,则转换应该会失败。

My rule of thumb is to ask myself, "given the delegate, what could I do with it? If I can pass in an argument which would break the method, the conversion should have failed. If the method can return something which would break the caller, the conversion should have failed."

在您的代码中,您可以调用:

In your code, you could have called:

_delegate(new object());

那时,可怜的 MyMethod 有一个参数 meant 的类型为 SomeObject ,但实际上 的类型为 object

At that point, poor MyMethod has a parameter which is meant to be of type SomeObject, but is actually of type object. This would be a Very Bad Thing, so the compiler stops it from happening.

这一切都更有意义吗?

这篇关于代表协方差混淆难题!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆