2016-09-27 60 views
1

简单代码:奇怪的动态类型参数的问题

class Program 
{ 
    static void Main(string[] args) 
    { 
     dynamic income = "test"; 
     var result = Test(income); // Why dynamic? 
     Test2(result); // WTF? 
    } 

    static string Test(string income) 
    { 
     return income; 
    } 

    static string Test2(int income) 
    { 
     return income.ToString(); 
    } 
} 

上面的代码编译没有错误,并在运行时异常执行:An unhandled exception of type Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in System.Core.dll

任何人都可以解释为什么result被确定为dynamic类型?

回答

10

当您将dynamic值传递给表达式时,该整个表达式将变为dynamic

动态的关键在于关闭所有类型检查;编译器将始终假定dynamic,即使代码显然是错误的。

+0

它是否记录在任何地方? –

+0

这是'dynamic'核心行为的一部分;看看它的文档。 – SLaks