Does C# pick the wrong type for var when parsing a dynamic object?

后端 未结 4 808
刺人心
刺人心 2020-12-16 16:51

I am using the following code to convert some Json into a dynamic object. When I use DateTime.Parse on a property of my dynamic type I would expect the var to guess that it\

4条回答
  •  眼角桃花
    2020-12-16 17:15

    There are two different concepts here

    1. dynamic: which is any type that is resolved at run-time
    2. var: which is implicit static typing that is performed at compile time

    So if you do

    var settings = new JavaScriptSerializer().Deserialize(json);
    var startDate = DateTime.Parse(settings.startDate);
    

    at compile time it is resolved to dynamic type and at run time it is resolved to a concrete type. Compiler checks the right part new JavaScriptSerializer().Deserialize(json);, which returns dynamic. At compile time this instructs compiler to drop all type-safty checks and live it till run time.

    This code

    var settings = new JavaScriptSerializer().Deserialize(json);
    DateTime startDate = DateTime.Parse(settings.startDate);
    

    explicitly says that the dynamic object is of concrete type, therefore compiler is able to infer the type, all its methods and is able to perform static type check at compile time.

提交回复
热议问题