c# - 奇怪的动态类型参数问题

标签 c# .net

简单的代码:

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/

相关文章:

c# - 建模问题(接口(interface)与抽象类)

c# - 如何使用 sql 查询在 SQL Server 中存储来自 C# 的哈希值

c# - 为什么#region 指令不能自动格式化?

c# - 输入字符串的格式不正确 C#

c# - System.Windows.Size 和 System.Drawing.Size 有什么区别?

.net - 如何通过 service/WebInvoke 方法控制 JSON 反序列化对象的属性名称(大小写)

.net - 什么是 .NET 文件夹搜索层次结构?

sql - Visual Studio 2019 架构比较未检测到差异

c# - 有没有办法检测 Windows 是否正在安装设备驱动程序?

c# - 我怎么知道图片何时加载到 Picturebox 中