Cannot assign a delegate of one type to another even though signature matches(即使签名匹配,也无法将一种类型的委托分配给另一种类型)
问题描述
我病态的好奇心让我想知道为什么以下失败:
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.
来自语言规范:
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);
这篇关于即使签名匹配,也无法将一种类型的委托分配给另一种类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:即使签名匹配,也无法将一种类型的委托分配给另一种类型
- 带问号的 nvarchar 列结果 2022-01-01
- 使用 rss + c# 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01