为什么不能将anon函数与动态参数一起使用? [英] Why can you not use anon function with a dynamic parameter?

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

问题描述

今天就碰到了

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

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<dynamic, dynamic>.但是请记住:

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<Func<dynamic, dynamic>>. 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.

因此,由于

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<dynamic, string>,如下所示:

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.

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

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