简单的代码:
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
类型?
最佳答案
当您将dynamic
值传递给表达式时,整个表达式将变为dynamic
。
动态的全部目的是关闭所有类型检查。即使代码明显错误,编译器也将始终采用dynamic
。
关于c# - 奇怪的动态类型参数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39732097/