我有以下问题
private int GetInt(dynamic a)
{
return 1;
}
private void UsingVar()
{
dynamic a = 5;
var x = GetInt(a);
}
Run Code Online (Sandbox Code Playgroud)
但是 x 仍然是动态的。我不明白为什么。

因为你的论点a的GetInt方法调用有型动态的,因此重载解析发生在运行时,而不是在编译时。
基于此:
如果方法调用中的一个或多个参数具有动态类型,或者方法调用的接收者是动态类型,则重载解决发生在运行时而不是编译时。
实际上,通过使用dynamic您正在使用后期绑定(推迟到稍后),这意味着编译器无法验证它,因为它不再使用任何静态类型分析。
解决方案是使用这样的演员表:
var x = (int)GetInt(a);
Run Code Online (Sandbox Code Playgroud)
以下是编译器如何处理您的代码:
private void UsingVar()
{
object arg = 5;
if (<>o__2.<>p__0 == null)
{
Type typeFromHandle = typeof(C);
CSharpArgumentInfo[] array = new CSharpArgumentInfo[2];
array[0] = CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType, null);
array[1] = CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null);
<>o__2.<>p__0 = CallSite<Func<CallSite, C, object, object>>
.Create(Microsoft.CSharp.RuntimeBinder.Binder
.InvokeMember(CSharpBinderFlags.InvokeSimpleName, "GetInt", null, typeFromHandle, array));
}
object obj = <>o__2.<>p__0.Target(<>o__2.<>p__0, this, arg);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
83 次 |
| 最近记录: |