为什么不能索引到一个ExpandoObject? [英] Why can't I index into an ExpandoObject?

查看:177
本文介绍了为什么不能索引到一个ExpandoObject?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

找东西到C#动态今天抓到时,我惊讶(我从来没有使用过不多,但最近我一直在与南希Web框架试验)。我发现我无法做到这一点:

 动态的expando =新ExpandoObject(); 

expando.name =约翰;

Console.WriteLine(Expando的[名称]);



最后一行抛出异常:



<块引用>

无法与适用[]索引类型为
'System.Dynamic.ExpandoObject




的表达

我理解的错误消息,但我不明白为什么会这样。我已经看过了ExpandoObject的文档,并明确实施的IDictionary<,> ,因而具有此[索引] 办法( MSDN )。为什么我不能打电话了吗?



当然,没有什么可以从向下转换的 ExpandoObject 阻止我一个字典手动,然后进行索引,但那种违抗点;它也没有解释Expando的是如何能够隐藏其接口之一的方法。



这是怎么回事吗?


< DIV CLASS =h2_lin>解决方案

Expando的是如何能够隐藏其接口之一的方法。




由于你正确的文档中发现的的索引是一个 显式接口实现。从显式接口实现教程




这是实现一个接口可以显式实现该接口的成员的类。当一个部件被明确实现的,它不能被通过一个类的实例访问,但仅通过该接口的一个实例。




这意味着你必须要引用转换为界面访问它:

 ((IDictionary的<弦乐,对象>)的expando)[名称] 


Something caught me by surprise when looking into C# dynamics today (I've never used them much, but lately I've been experimenting with the Nancy web framework). I found that I couldn't do this:

dynamic expando = new ExpandoObject();

expando.name = "John";

Console.WriteLine(expando["name"]);

The last line throws an exception:

Cannot apply indexing with [] to an expression of type 'System.Dynamic.ExpandoObject'

I understand the error message, but I don't understand why this is happening. I have looked at the documentation for ExpandoObject and it explicitly implements IDictionary<,> and thus has a this.[index] method (MSDN). Why can't I call it?

Of course, there's nothing to stop me from downcasting the ExpandoObject to a dictionary manually and then indexing into it, but that kind of defies the point; it also doesn't explain how the Expando was able to hide the method of one of its interfaces.

What's going on here?

解决方案

how the Expando was able to hide the method of one of its interfaces.

Because as you correctly found out in the documentation, the indexer is an explicit interface implementation. From Explicit Interface Implementation Tutorial:

A class that implements an interface can explicitly implement a member of that interface. When a member is explicitly implemented, it cannot be accessed through a class instance, but only through an instance of the interface.

This means you'll have to cast the reference to the interface to access it:

((IDictionary<String, Object>)expando)["name"]

这篇关于为什么不能索引到一个ExpandoObject?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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