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.
这一切更有意义吗?
这篇关于委托协方差混淆难题!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:委托协方差混淆难题!
基础教程推荐
- SSE 浮点算术是否可重现? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- c# Math.Sqrt 实现 2022-01-01