在C#中创建动态扩展方法? [英] Creating a dynamic extension method in C#?
问题描述
是否可以解决此错误:
public static class LayoutExtensions
{
/// <summary>
/// Verifies if an object is DynamicNull or just has a null value.
/// </summary>
public static bool IsDynamicNull(this dynamic obj)
{
return (obj == null || obj is DynamicNull);
}
编译时间
Error: The first parameter of an extension method
cannot be of type 'dynamic'
$ b类型$ b
推荐答案
否。参见 https://stackoverflow.com/a/5311527/613130
使用 dynamic
对象时,无法通过扩展方法语法调用扩展方法。明确说明:
When you use a dynamic
object, you can't call an extension method through the "extension method syntax". To make it clear:
int[] arr = new int[5];
int first1 = arr.First(); // extension method syntax, OK
int first2 = Enumerable.First(arr); // plain syntax, OK
这两个都可以,但是动态的
Both of these are ok, but with dynamic
dynamic arr = new int[5];
int first1 = arr.First(); // BOOM!
int first2 = Enumerable.First(arr); // plain syntax, OK
如果您知道 dynamic
对象起作用。 动态
变量/字段/ ...只是对象
变量/字段/ ...(加上属性),C#编译器知道应该将其视为 dynamic
。 动态处理是什么意思?这意味着生成的代码而不是直接使用变量,而是使用反射在对象类型内搜索所需的方法/属性/ ...(因此,在这种情况下,在 int []
类型)。显然,反射不能绕过所有已加载的程序集,以寻找可能在任何地方的扩展方法。
This is logical if you know how dynamic
objects work. A dynamic
variable/field/... is just an object
variable/field/... (plus an attribute) that the C# compiler knows that should be treated as dynamic
. And what does "treating as dynamic" means? It means that generated code, instead of using directly the variable, uses reflection to search for required methods/properties/... inside the type of the object (so in this case, inside the int[]
type). Clearly reflection can't go around all the loaded assemblies to look for extension methods that could be anywhere.
这篇关于在C#中创建动态扩展方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!