[英]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.