委托协方差混淆难题!

Delegate Covariance Confusion Conundrum!(委托协方差混淆难题!)

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

问题描述

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

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) {}
}

这现在演示了逆变.

我的经验法则是问自己,给定委托,我能用它做什么?如果我可以传入一个会破坏方法的参数,那么转换应该失败.如果方法可以返回一些会破坏调用者,转换应该失败."

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 有一个参数 意味着SomeObject 类型,但 实际上是object 类型的 em>.这将是一件非常糟糕的事情,因此编译器会阻止它发生.

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.

这一切更有意义吗?

这篇关于委托协方差混淆难题!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:委托协方差混淆难题!

基础教程推荐