为什么不能使用带有动态参数的匿名函数? [英] Why can you not use anon function with a dynamic parameter?

查看:25
本文介绍了为什么不能使用带有动态参数的匿名函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天刚遇到这个

匿名函数或方法组不能用作成分动态绑定操作的值.

An anonymous function or method group cannot be used as a constituent value of a dynamically bound operation.

尝试做的时候

static R ifNotNull<R>(dynamic o, Func<dynamic, R> returnFunc, R otherwise) {
    return ReferenceEquals(null, o) ? otherwise : returnFunc(o);
}

并与

dynamic firstAddress = ...;
return ifNotNull<string>(firstAddress, (a) => a.address_1, null)

现在对动态的大多数限制对我来说都有意义 - 你不能使用扩展方法,因为编译器应该如何决定将它编译成哪个静态?但我在这里不明白.混乱从何而来?究竟是什么限制?

Now most of the limitations on dynamics make sense to me - you can't use an extension method because how is the compiler supposed to decide which static to compile it to? But I don't get this here. Where does the confusion come in? What exactly is the limitation?

推荐答案

什么是静态类型兰巴 a =>a.address_1?您可能很想说这是一个 Func.但请记住:

What is the static type of the lamba a => a.address_1? You may be tempted to say it's a Func<dynamic, dynamic>. But remember:

lambda 表达式是一个匿名函数,您可以使用它创建委托或表达式树类型.

A lambda expression is an anonymous function that you can use to create delegates or expression tree types.

所以也许它是一个 Expression>.lamda 本身没有单一的静态类型.

So maybe it's an Expression<Func<dynamic, dynamic>>. A lamda by itself doesn't have a single static type.

现在通常类型推断会发现您将 Lamba 传递给一个接受 Func 的函数,并且它将在编译时转换为委托.但是,当您使用动态参数调用时 方法调用是动态调度的.

Now normally type inference would figure out that you're passing the lamba to a function that takes a Func and it will be converted to a delegate at compile time. However when you are calling with dynamic arguments the method call is dispatched dynamically.

如果你有一个带有动态参数的方法调用,它会被分派动态, 时期.在运行时绑定期间,所有静态类型您的论点中的一部分是已知的(重点是我的),并且为动态选择了类型参数基于它们的实际值.

If you have a method call with a dynamic argument, it is dispatched dynamically, period. During the runtime binding, all the static types of your arguments are known (emphasis mine), and types are picked for the dynamic arguments based on their actual values.

因此,您的方法采用 Func 的事实并未考虑在内,因为 直到运行时才确定实际的方法调用,因此没有类型推断.

So the fact that your method takes a Func isn't take into account, since the actual method call isn't determined until runtime so there is no type inference.

要编译它,您必须将您的lamba转换为Func,如下所示:

To get this to compile you'll have to cast your lamba to a Func<dynamic, string> as below:

return ifNotNull<string>(firstAddress, new Func<dynamic, string>((a) => a.address_1), null);

现在你的 lamda 的静态类型是已知的.

Now the static type of your lamda is known.

这篇关于为什么不能使用带有动态参数的匿名函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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