C#DLR,数据类型推断与动态关键字 [英] C# DLR, Datatype inference with Dynamic keyword

查看:115
本文介绍了C#DLR,数据类型推断与动态关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是问:

为什么withOffset变量被推断为 动态作为解析方法返回结构体

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

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

和后显式类型转换将其带回结构?

and after explicit cast its back to Struct?

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

由于DateTimeOffset.Parse的返回类型是的DateTimeOffset,和编译器必须知道这一点。牢记这一点,什么都的方法调用它在运行时,返回的是永远的DateTimeOffset。

since the return type of DateTimeOffset.Parse is DateTimeOffset, and the compiler must know that. keeping that in mind, what ever method it invoke at runtime, the return is always DateTimeOffset.

的规格告诉

由于您的方法以动态的作为一个参数,它有资格为动态绑定

Since your method takes dynamic as an argument, it qualifies for "dynamic binding"

有点腥。

什么是点中有这样的规范?还是在这情况下DateTimeOffset.Parse不会返回STRUCT(DLR遗忘的时刻。)?

What's point in having such specification? OR in which circumstance DateTimeOffset.Parse will not return STRUCT ( forgetting DLR for moment.. )?

编译器必须要聪明,如果所有方法/超载类具有相同的返回类型,以获得性能优势在长期运行。

Compiler need to be clever, if all methods/overload in the class have same return type to gain performance benefit in long run.

推荐答案

在使用动态,整个EX pression是在编译时当作动态EX pression 的,这会导致编译器把一切动态,并获得运行时绑定。

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.

这是在C#语言规范7.2说明:

This is explained in 7.2 of the C# Language specification:

在不涉及动态EX pressions,C#默认为静态绑定,这意味着,组成前pressions编译时类型在选择过程中使用。然而,构成前pressions在上面列出的操作,当一个是动态的前pression,操作,而不是动态绑定

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节),它有一个声明为动态将被评估为<$ C的任何元素$ C>动态,其结果将是一个动态

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.

这是因为在低于行str是动态

this is because in below line str is dynamic

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

在编译的时候str是动态的,str的类型结识在运行时这是唯一的原因编译器治疗withOffset动态

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

它知道你str是被转换成datetime结构,但对编译器,它搞懂只能在运行...

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

这篇关于C#DLR,数据类型推断与动态关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆