即使签名匹配,也无法将一种类型的委托分配给另一种类型

发布于 2024-10-08 01:21:40 字数 340 浏览 4 评论 0原文

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

// 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!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浅唱ヾ落雨殇 2024-10-15 01:21:40

C# 对“结构”类型的支持非常有限。特别是,您不能简单地从一种委托类型转换为另一种委托类型,因为它们的声明是相似的。

从语言规范来看:

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

尝试以下之一:

// 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);

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.

From the language specification:

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.

Try one of:

// 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);
若沐 2024-10-15 01:21:40

这是一个类似的问题:为什么不能编译?

// declared somewhere
struct Foo {
    public int x;
    public int y;
}

struct Bar {
    public int x;
    public int y;
}

// ... in a method body
Foo item = new Foo { x = 1, y = 2 };

Bar b1 = item; // doesn't compile, and casting doesn't compile
Bar b2 = new Bar { x = 1, y = 2 }; // compiles!

在这种情况下,演员阵容不工作似乎更自然一些,但实际上是同样的原因。

Here's a similar question: why doesn't this compile?

// declared somewhere
struct Foo {
    public int x;
    public int y;
}

struct Bar {
    public int x;
    public int y;
}

// ... in a method body
Foo item = new Foo { x = 1, y = 2 };

Bar b1 = item; // doesn't compile, and casting doesn't compile
Bar b2 = new Bar { x = 1, y = 2 }; // compiles!

In this case it seems a little more natural for the cast to not work, but it's really the same reason.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文