c# - C# 在解析动态对象时是否为 var 选择了错误的类型?

标签 c# c#-4.0 dynamic var

我正在使用以下代码将一些 Json 转换为动态对象。当我在我的动态类型的属性上使用 DateTime.Parse 时,我希望 var 猜测它的类型是 DateTime ... 相反,它保持动态。这不可能是对的,对吗?

完整示例如下。

var settings = new JavaScriptSerializer().Deserialize<dynamic>(json);

var startDate = DateTime.Parse(settings.startDate);
var endDate = DateTime.Parse(settings.endDate);
var userId = int.Parse(settings.userId);

startDate、endDate 和 userId 仍然是动态的,这意味着我不能在以后的 Lambda 表达式中使用它们。显然,我可以通过以下方式修复代码:

DateTime startDate = DateTime.Parse(settings.startDate);
DateTime endDate = DateTime.Parse(settings.endDate);
int userId = int.Parse(settings.userId);

..但编译器似乎做出了“错误的猜测”。谁能给我解释一下?

谢谢

最佳答案

..but it seems like the compiler is making a 'bad guess'. Can anyone explain this to me?

当您使用 dynamic 时,整个表达式在编译时被视为一个动态表达式,这导致编译器将所有内容都视为动态并获得运行时绑定(bind).

这在 C# 语言规范的 7.2 中有解释:

When no dynamic expressions are involved, C# defaults to static binding, which means that the compile-time types of constituent expressions are used in the selection process. However, when one of the constituent expressions in the operations listed above is a dynamic expression, the operation is instead dynamically bound.

这基本上意味着大多数操作(类型在规范的 7.2 节中列出)具有任何声明为 dynamic 的元素将被评估为 dynamic,结果将是一个dynamic

在你的例子中,这个声明:

var settings = new JavaScriptSerializer().Deserialize<dynamic>(json);

使用动态,因此,它被视为动态表达式。由于“方法调用”是受绑定(bind) (7.2) 约束的 C# 操作之一,编译器将其视为动态绑定(bind),这导致其计算结果为:

dynamic settings = new JavaScriptSerializer().Deserialize<dynamic>(json);

这反过来又导致 DateTime.Parse 表达式被动态绑定(bind),这反过来又使它们返回 dynamic

当您执行 DateTime startDate = DateTime.Parse(settings.startDate); 时,您的“修复”有效,因为这会强制隐式动态转换(在规范的第 6.1.8 节中描述) DateTime.Parse 方法到 DateTime 的结果:

An implicit dynamic conversion exists from an expression of type dynamic to any type T. The conversion is dynamically bound (§7.2.2), which means that an implicit conversion will be sought at run-time from the run-time type of the expression to T. If no conversion is found, a run-time exception is thrown.

在这种情况下,转换是有效的,因此您可以有效地将所有内容切换回静态绑定(bind)。

关于c# - C# 在解析动态对象时是否为 var 选择了错误的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9381690/

相关文章:

c# - 将目标框架从 v4.0 更改为 v3.5 后找不到命名空间

c# - 即使没有记住我,我是否必须在客户端机器上存储 cookie?

php - 动态加载网站的一部分 - 更改网址

搜索引擎的动态页面

c# - 从 LINQ 数据库查询中的整数返回枚举名称

c# - 如何在触发器的 setter 中设置部分文本的前景?

c# - Microsoft.Practices.EnterpriseLibrary.Data : execute multiple statements in one transaction

c# - 如何隐藏asp.net 向导控件步骤名称?

c# - 如何在没有污染方法的情况下登录?

php - 从数据库中获取 ID 计数并生成指向新闻的动态链接