如何将委托 R Function(T t) 转换为 Func

发布于 2025-01-08 09:26:48 字数 350 浏览 2 评论 0原文

我有定义以下助手的遗留代码

public delegate R Function<T, R>(T t);

但我想提供 Func

转换尝试无法编译

无法将类型“System.Func”转换为“Rhino.Mocks.Function

有没有一种方法不仅可以编译,而且可以运行时的函数?

I've got legacy code that defined the following helper

public delegate R Function<T, R>(T t);

But I want to supply a Func<T,TResult>

casting attempts fail to compile

Cannot convert type 'System.Func<T,TResult>' to 'Rhino.Mocks.Function<T,TResult>'

Is there a way that not only compiles, but functions at runtime?

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

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

发布评论

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

评论(3

别理我 2025-01-15 09:26:48

问题是您尝试组合两种不同的委托类型:FuncFunction。尽管它们具有相同的签名,但它们是不同的,因此是不兼容的类型。

使用 lambda 在两者之间创建转换层。

Func<T, TResult> func = ...;
TheMethod(x => func(x));

The problem is you are trying to combine two different delegate types: Func<T, TResult> and Function<T, TResult>. Even though they have the same signature they are different, and hence incompatible, types.

Use a lambda to create a conversion layer between the two.

Func<T, TResult> func = ...;
TheMethod(x => func(x));
陌路终见情 2025-01-15 09:26:48

Jared 和 phoog 都是正确的。做同样事情的第三种方法(只是为了完善它)是:

Func<int, string> func = i => i.ToString();
Function<int, string> function = func.Invoke;

也就是说,新委托是第一个委托的调用方法的委托,它具有正确的签名。

一个人必须这样做是非常令人烦恼的。如果我们今天从头开始设计运行时,了解我们现在对人们如何使用委托类型的了解,我认为每个签名可能都会有一个内置委托类型(就像有一个“一维整数数组”类型),或者委托类型之间存在“结构标识”。下次为虚拟机设计类型系统时,请记住这一点。

Jared and phoog are both correct. A third way to do the same thing, just to round it out, is:

Func<int, string> func = i => i.ToString();
Function<int, string> function = func.Invoke;

That is, the new delegate is a delegate to the invoke method of the first delegate, which has the correct signature.

That one has to do this is vexing in the extreme. Were we designing the runtime from scratch today, knowing what we now known about how people use delegate types, I think it likely that there would either be one built in delegate type for each signature (much as there is one "single dimensional array of integers" type), or that there would be "structural identity" amongst delegate types. Next time you design the type system for a virtual machine, keep that in mind.

怪我入戏太深 2025-01-15 09:26:48

您可以按照 JaredPar 的建议创建一个 lambda,或者将一个 lambda 传递给另一个的构造函数:

Func<int, string> f1 = i => i.ToString();
Function<int, string> f2 = new Function<int, string>(f1);

You can create a lambda as JaredPar suggests, or pass one to the constructor of the other:

Func<int, string> f1 = i => i.ToString();
Function<int, string> f2 = new Function<int, string>(f1);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文