问题描述
我使用下面的代码部分的Json转换成动态对象。当我使用DateTime.Parse我的动态类型的属性我期望VAR猜测,它的类型是一个DateTime ......相反,它保持为动态。这不可能是正确的,可以吗?
下面完整的示例。
VAR设置=新的JavaScriptSerializer()反序列化<动态>(JSON);
变种的startDate = DateTime.Parse(settings.startDate);
VAR结束日期= DateTime.Parse(settings.endDate);
VAR用户id = int.Parse(settings.userId);
的startDate,结束日期和用户id都仍然是动态的,这意味着我再不能在以后的LAMBDA使用它们表达式。很显然,我可以修复的代码:
日期时间的startDate = DateTime.Parse(settings.startDate);
DateTime的结束日期= DateTime.Parse(settings.endDate);
INT用户id = int.Parse(settings.userId);
..但似乎编译器做一个坏的猜测。谁能解释这样对我?
感谢
这基本上意味着大多数操作(类型在规范的7.2节所列),它有一个声明为动态
将被评估为动态任何元素
,结果将是一个动态
。
在你的情况,这种说法:
VAR设置=新。的JavaScriptSerializer()反序列化<动态>(JSON);
使用动态,因此,它getst reated作为一个动态的表情。由于方法调用是C#操作主题之一结合(7.2),编译器将这种动态绑定,这将导致该评价为:
动态设置=新的JavaScriptSerializer()反序列化<动态>(JSON);
这反过来又导致 DateTime.Parse
表达式是动态绑定的,这反过来又使他们返回动态
。
您的作品修复的时候您日期时间的startDate = DateTime.Parse(settings.startDate);
,因为这种力量的结果的隐式动态转换(在规范第6.1.8所述) DateTime.Parse方法为DateTime:
When you use dynamic
, the entire expression is treated at compile time as a dynamic expression, which causes the compiler to treat everything as dynamic and get run-time binding.
This is explained in 7.2 of the C# Language specification:
This basically means that most operations (the types are listed in section 7.2 of the spec) which have any element that is declared as dynamic
will be evaluated as dynamic
, and the result will be a dynamic
.
In your case, this statement:
var settings = new JavaScriptSerializer().Deserialize<dynamic>(json);
Uses dynamic, so, it getst reated as a dynamic expression. Since "Method invocation" is one of the C# operations subject to binding (7.2), the compiler treats this as dynamic bound, which causes this to evaluate to:
dynamic settings = new JavaScriptSerializer().Deserialize<dynamic>(json);
This, in turn, causes the DateTime.Parse
expressions to be dynamic bound, which in turn makes them return dynamic
.
Your "fix" works when you do DateTime startDate = DateTime.Parse(settings.startDate);
because this forces an implicit dynamic conversion (described in section 6.1.8 of the spec) of the result of the DateTime.Parse method to a DateTime:
In this case, the conversion is valid, so you effectively switch everything back to static binding from then on.
这篇关于请问C#解析动态对象时,选择了错误的类型变种?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!