Creating a dynamic extension method in C#?

流过昼夜 提交于 2019-12-10 13:39:50

问题


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'  

回答1:


No. See https://stackoverflow.com/a/5311527/613130

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

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.




回答2:


All classes derived by object class. Maybe try this code

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


来源:https://stackoverflow.com/questions/29743568/creating-a-dynamic-extension-method-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!