如何在具有ExpandoObject类型的对象上应用扩展方法? [英] How to apply an Extension Method on the object having the type of ExpandoObject?

查看:95
本文介绍了如何在具有ExpandoObject类型的对象上应用扩展方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

public static class DynamicExtensions

    public static void Add(this ExpandoObject obj, string path){
        dynamic _obj = obj;
        if (_obj == null) throw new ArgumentNullException("obj");
        _obj.path = path;
    }
}

但是当我以这种方式调用它时,出现了'System.Dynamic.ExpandoObject'不包含'Add'的定义"的错误:

But I got the error of "'System.Dynamic.ExpandoObject' does not contain a definition for 'Add'", when I call it in this way:

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

如何解决?

提前谢谢!

推荐答案

问题是将dynamic与扩展方法一起使用-两者根本不在一起.很好:

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

...但是只有dynamic,不支持扩展方法.

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

根据C#5规范的7.6.5.2节:

From section 7.6.5.2 of the C# 5 spec:

在其中一种形式的方法调用(第7.5.5.1节)中

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 )

如果调用的正常处理未找到适用的方法,则尝试将构造作为扩展方法调用进行处理. 如果expr或任何arg具有动态编译时类型,则扩展方法将不适用.

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.

虽然编译器可以记住要应用扩展方法必须检查的using指令,但实际上并没有这样做-也许是出于性能原因,或者可能只是因为感觉到从事很多工作,却获得相对较少的收益.

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.

这篇关于如何在具有ExpandoObject类型的对象上应用扩展方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆