C# DLR, Datatype inference with Dynamic keyword

后端 未结 2 484
暖寄归人
暖寄归人 2021-02-10 03:38

Just Asking :

Why \'withOffset\' variable is inferred as dynamic as Parse method returns Struct ?

dynamic str         


        
2条回答
  •  一整个雨季
    2021-02-10 04:01

    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:

    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.

    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.


    this is because in below line str is dynamic

             dynamic str = "22/11/2013 10:31:45 +00:01";
            var withOffset = DateTimeOffset.Parse(str);
    

    At compile time str is dynamic, the type of str get to know at runtime only that is the reason compiler treat withOffset as dynamic


    its known to you that str is get converted to datetime structure but for compiler that it get to know only at runtime...

提交回复
热议问题