推断类型和动态类型 [英] Inferred Type and Dynamic typing

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

问题描述

在编程语言中,推断类型和动态类型有什么区别?我知道动态类型,但不知道动态类型与推断类型有何不同?有人可以提供一些例子的解释吗?

In programming language what is the difference between Inferred Type and Dynamic typing? I know about Dynamic typing but don't get how dynamic typing is differ from Inferred Type and how? Could someone please provide explanation with some example?

推荐答案

  • 推断类型 = 在编译时设置一次.实际上,推断部分只是为了节省时间,因为如果编译器可以计算出来,您就不必键入 Typename.

    • Inferred type = set ONCE and at compile time. Actually the inferred part is only a time saver in that you don't have to type the Typename IF the compiler can figure it out.

      类型推断通常与静态类型结合使用(就像 swift 的情况一样)(http://en.wikipedia.org/wiki/Type_inference)

      Type Inference is often used in conjunction static typing (as is the case with swift) (http://en.wikipedia.org/wiki/Type_inference)

      动态类型 = 无固定类型 -> 类型可以在运行时改变

      Dynamic type = no fixed Type -> type can change at runtime

      静态&推断示例:

      static & inferred example:

      var i = true; //compiler can infer that i most be of type Bool
      i = "asdasdad" //invalid because compiler already inferred i is an Bool!
      

      等于

      var i: bool = true; //You say i is of type Bool
      i = "asdasdad" //invalid because compiler already knows i is a Bool!
      

      ==> 类型推断可以让您在编译器可以看到的情况下拼出类型

      ==> type inference saves you spell out the type if the compiler can see it

      但是如果它是动态的(例如 objC),因为类型仅基于运行时的内容

      BUT if it were dynamic that would work (e.g. objC) as the type is only based on the content at RUNtime

      id i = @YES; //NSNumber
      i = @"lalala"; //NSString
      i = @[@1] //NSArray
      

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

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