简体   繁体   English

为什么“((dynamic)dictionary).MyKey”抛出RuntimeBinderException?

[英]Why “((dynamic) dictionary).MyKey” throws a RuntimeBinderException?

Let's imagine this simple snippet: 让我们想象一下这个简单的片段:

Dictionary<string,string> dictionary = new Dictionary<string, string>();
dictionary.Add("MyKey", "MyValue");

string val;
dictionary.TryGetValue("MyKey", out val);
Console.WriteLine(val); // print "MyValue"

Console.WriteLine(((dynamic)dictionary).MyKey); // throws a RuntimeBinderException

Why a RuntimeBinderException is thrown at last line? 为什么在最后一行抛出RuntimeBinderException

Thanks for your help! 谢谢你的帮助!

Because Dictionary<string, string> does not have a member MyKey . 因为Dictionary<string, string>没有成员MyKey Dynamic typing does not create members on the fly. 动态键入不会动态创建成员。

To put it in perspective, what you're trying to do is equivalent to ((dynamic) dictionary).get_MyKey() . ((dynamic) dictionary).get_MyKey()角度来说,您想要做的事情等效于((dynamic) dictionary).get_MyKey() Clearly, the dictionary does not have a get_MyKey() method. 显然,该词典没有get_MyKey()方法。

暂无
暂无

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

相关问题 事件回调<dynamic>抛出 RuntimeBinderException</dynamic> - EventCallback<dynamic> throws RuntimeBinderException 为什么“动态”ExpandoObject 即使包含属性定义也会抛出 RuntimeBinderException? - Why 'dynamic' ExpandoObject throws RuntimeBinderException even if it contains the definition for a property? 动态转换为ObjectHandle会引发RuntimeBinderException - Casting dynamic to ObjectHandle throws RuntimeBinderException 动态属性分配引发RuntimeBinderException - Dynamic Property Assignment Throws RuntimeBinderException 在嵌套在子文件夹中的Partial中使用@model dynamic会引发RuntimeBinderException - Using @model dynamic in a Partial nested in a subfolder throws RuntimeBinderException Dictionary &lt;&gt;。ContainsKey给出RuntimeBinderException - Dictionary<>.ContainsKey gives RuntimeBinderException 为什么动态对象的分配会抛出RuntimeBinderException? - Why does the assignment from a dynamic object throw a RuntimeBinderException? C#动态-“ RuntimeBinderException” - C# Dynamic - “RuntimeBinderException” 将C#动态与COM对象一起使用会引发RuntimeBinderException,以记录已实现接口的方法 - Using C# dynamic with COM object throws RuntimeBinderException for documented method of implemented interface 从继承的接口调用Method时传递动态参数会引发RuntimeBinderException - Passing a dynamic parameter throws RuntimeBinderException when calling Method from Inherited interface
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM