How to apply an Extension Method on the object having the type of ExpandoObject?

后端 未结 2 411
遥遥无期
遥遥无期 2021-01-21 16:31

Here is my code:

public static class DynamicExtensions

    public static void Add(this ExpandoObject obj, string path){
        dynamic _obj = obj;
        if (         


        
2条回答
  •  轮回少年
    2021-01-21 17:19

    The problem is using dynamic with extension methods - the two just don't go together. This would be fine:

    ExpandoObject obj = new ExpandoObject();
    obj.Add("p1");
    

    ... but with just dynamic, there's no extension method support.

    From section 7.6.5.2 of the C# 5 spec:

    In a method invocation (§7.5.5.1) of one of the forms

    expr . identifier ( )
    expr . identifier ( args )
    expr . identifier < typeargs > ( )
    expr . identifier < typeargs > ( args )
    

    if the normal processing of the invocation finds no applicable methods, an attempt is made to process the construct as an extension method invocation. If expr or any of the args has compile-time type dynamic, extension methods will not apply.

    While the compiler could remember the using directives which it would have to check to apply extension methods, it just doesn't - perhaps for performance reasons, or perhaps because it was just felt to be a lot of work for relatively little benefit.

提交回复
热议问题