且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么不能使用带有动态参数的匿名函数?

更新时间:2023-11-02 15:46:34

什么是静态类型兰巴 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.