【发布时间】:2014-07-15 14:47:28
【问题描述】:
我遇到了在 C# 中使用动态变量的问题。这是在编写 NancyFx 路由模块时出现的,但我已将问题归结为以下示例。虽然我在原始代码中收到了一个不同的异常,但示例代码仍然抛出了一个我认为是错误的异常。有没有人看到这里发生了什么,或者其他人遇到过类似的问题?
请注意,以下帖子可能相关: StackOverflowException when accessing member of generic type via dynamic: .NET/C# framework bug? System.Dynamic bug?
代码:
class Program
{
static void Main(string[] args)
{
var dictionary = new Dictionary<string, object>();
dictionary.Add("number", 12);
var result = MethodUsesExplicitDeclaration(dictionary);
var result2 = MethodUsesImplicitDeclaration(dictionary);
}
static dynamic MethodUsesExplicitDeclaration(dynamic reallyDictionary)
{
// this works, ostensibly because the local variable is explicitly declared
IDictionary<string, object> dictionary = CastDictionary(reallyDictionary);
return dictionary.Get<int>("number");
}
static dynamic MethodUsesImplicitDeclaration(dynamic reallyDictionary)
{
// this throws an exception, and the only difference is
// that the variable declaration is implicit
var dictionary = CastDictionary(reallyDictionary);
return dictionary.Get<int>("number");
}
static IDictionary<string, object> CastDictionary(dynamic arg)
{
return arg as IDictionary<string, object>;
}
}
static class Extensions
{
public static T Get<T>(this IDictionary<string, object> dictionary, string key)
{
var value = dictionary[key];
if (value is T)
return (T)value;
throw new InvalidOperationException();
}
}
例外:Microsoft.CSharp.RuntimeBinder.RuntimeBinderException was unhandled
HResult=-2146233088
Message='System.Collections.Generic.Dictionary<string,object>' does not contain a definition for 'Get'
Source=Anonymously Hosted DynamicMethods Assembly
StackTrace:
at CallSite.Target(Closure , CallSite , Object , String )
at System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,TRet](CallSite site, T0 arg0, T1 arg1)
at DynamicBug.Program.MethodUsesImplicitDeclaration(Object reallyDictionary) in c:\TFS\UnreleasedCode\POC\DynamicBug\DynamicBug\Program.cs:line 28
at DynamicBug.Program.Main(String[] args) in c:\TFS\UnreleasedCode\POC\DynamicBug\DynamicBug\Program.cs:line 16
InnerException:
【问题讨论】:
-
好像这个问题已经回答了here。
-
我不相信stackoverflow.com/questions/258988/… 解决了同样的问题。示例代码不会尝试在声明为动态的变量上使用扩展方法,而是在返回接口类型的方法的结果上使用它。因此,在执行扩展方法的方法的两个版本中,扩展方法适用的类型都不是动态的。
-
我可以问原始问题的另一种方式是
var变量声明何时不应该像您分配给它的值的类型一样? -
Jon Skeet 引用的响应的第一部分指出,“动态查找将无法找到扩展方法。”您收到
Get不存在的错误。Get是一种扩展方法。似乎它适用得很好。如果您将该行更改为return Extensions.Get<int>(dictionary, "number");,那么它将按预期执行。 -
Cédric Bignon's answer 解释了发生这种情况的原因,包括 C# 规范中定义此行为的位置。