简体   繁体   English

在C#中创建动态扩展方法?

[英]Creating a dynamic extension method in C#?

Is it possible to workaround this error: 是否可以解决此错误:

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);
    }

Compile time 编译时间

Error: The first parameter of an extension method 
       cannot be of type 'dynamic'  

No. See https://stackoverflow.com/a/5311527/613130 不。请参阅https://stackoverflow.com/a/5311527/613130

When you use a dynamic object, you can't call an extension method through the "extension method syntax". 使用dynamic对象时,无法通过“扩展方法语法”调用扩展方法。 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

dynamic arr = new int[5];
int first1 = arr.First(); // BOOM!
int first2 = Enumerable.First(arr); // plain syntax, OK

This is logical if you know how dynamic objects work. 如果您知道dynamic对象的工作原理,这是合乎逻辑的 A dynamic variable/field/... is just an object variable/field/... (plus an attribute) that the C# compiler knows that should be treated as dynamic . dynamic变量/ field / ...只是一个object变量/ field / ...(加上一个属性),C#编译器知道它应该被视为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). 这意味着生成的代码,而不是直接使用变量,使用反射来搜索对象类型内所需的方法/属性/ ...(所以在这种情况下,在int[]类型内)。 Clearly reflection can't go around all the loaded assemblies to look for extension methods that could be anywhere. 很明显,反射不能绕过所有加载的程序集以查找可能在任何地方的扩展方法。

All classes derived by object class. 所有类都是由对象类派生的。 Maybe try this code 也许试试这个代码

public static bool IsDynamicNull(this object obj)
{
    return (obj == null || obj is DynamicNull);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM