即使签名匹配,也不能将一种类型的委托分配给另一种类型 [英] Cannot assign a delegate of one type to another even though signature matches

查看:118
本文介绍了即使签名匹配,也不能将一种类型的委托分配给另一种类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的病态好奇心让我想知道为什么会失败:

My morbid curiosity has me wondering why the following fails:

// declared somewhere
public delegate int BinaryOperation(int a, int b);

// ... in a method body
Func<int, int, int> addThem = (x, y) => x + y;

BinaryOperation b1 = addThem; // doesn't compile, and casting doesn't compile
BinaryOperation b2 = (x, y) => x + y; // compiles!


推荐答案

C#对结构打字的支持非常有限。特别是,你不能从一个委托类型转换到另一个代理类型,因为它们的声明是相似的。

C# has very limited support for "structural" typing. In particular, you can't cast from one delegate-type to another simply because their declarations are similar.

从语言规范: / p>

From the language specification:


C#中的代理类型是
等价物,而不是结构上的
等价物。具体来说,两个
不同的委托类型的
相同的参数列表和返回类型
被认为是不同的委托
类型。

Delegate types in C# are name equivalent, not structurally equivalent. Specifically, two different delegate types that have the same parameter lists and return type are considered different delegate types.

尝试以下一种:

// C# 2, 3, 4 (C# 1 doesn't come into it because of generics)
BinaryOperation b1 = new BinaryOperation(addThem);

// C# 3, 4
BinaryOperation b1 = (x, y) => addThem(x, y);
var b1 = new BinaryOperation(addThem);

这篇关于即使签名匹配,也不能将一种类型的委托分配给另一种类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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