如何将委托 R Function(T t) 转换为 Func?
我有定义以下助手的遗留代码
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题是您尝试组合两种不同的委托类型:
Func
和Function
。尽管它们具有相同的签名,但它们是不同的,因此是不兼容的类型。使用 lambda 在两者之间创建转换层。
The problem is you are trying to combine two different delegate types:
Func<T, TResult>
andFunction<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.
Jared 和 phoog 都是正确的。做同样事情的第三种方法(只是为了完善它)是:
也就是说,新委托是第一个委托的调用方法的委托,它具有正确的签名。
一个人必须这样做是非常令人烦恼的。如果我们今天从头开始设计运行时,了解我们现在对人们如何使用委托类型的了解,我认为每个签名可能都会有一个内置委托类型(就像有一个“一维整数数组”类型),或者委托类型之间存在“结构标识”。下次为虚拟机设计类型系统时,请记住这一点。
Jared and phoog are both correct. A third way to do the same thing, just to round it out, is:
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.
您可以按照 JaredPar 的建议创建一个 lambda,或者将一个 lambda 传递给另一个的构造函数:
You can create a lambda as JaredPar suggests, or pass one to the constructor of the other: