PowerShell 是强类型语言吗? [英] Is PowerShell a strongly-typed language?

查看:36
本文介绍了PowerShell 是强类型语言吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PowerShell 绝对属于动态语言的范畴,但它会被视为强类型吗?

PowerShell is definitely in the category of dynamic languages, but would it be considered strongly typed?

推荐答案

围绕该术语存在一定程度的混淆.本文解释了一个有用的类型分类法系统.

There is a certain amount of confusion around the terminlogy. This article explains a useful taxonomy of type systems.

PowerShell 是动态的、隐式类型的:

PowerShell is dynamically, implicit typed:

> $x=100
> $x=dir

无类型错误 - 变量可以在运行时更改其类型.这就像 PythonPerlJavaScript 但不同于 C++Java, C#

No type errors - a variable can change its type at runtime. This is like Python, Perl, JavaScript but different from C++, Java, C#, etc.

然而:

> [int]$x = 100
> $x = dir
Cannot convert "scripts-2.5" to "System.Int32".

因此,如果您愿意,它还支持显式 类型的变量.然而,类型检查是在运行时而不是编译时完成的,所以它不是静态类型的.

So it also supports explicit typing of variables if you want. However, the type checking is done at runtime rather than compile time, so it's not statically typed.

我看到有人说 PowerShell 使用类型推断(因为您不必声明变量的类型),但我认为这是错误的说法.类型推断是在编译时进行类型检查的系统的一项功能(如 C# 中的var").PowerShell 只在运行时检查类型,因此它可以检查实际值而不是进行推理.

I have seen some say that PowerShell uses type inference (because you don't have to declare the type of a variable), but I think that is the wrong words. Type inference is a feature of systems that does type-checking at compile time (like "var" in C#). PowerShell only checks types at runtime, so it can check the actual value rather than do inference.

但是,有一些自动类型转换正在进行:

However, there is some amount of automatic type-conversion going on:

> [int]$a = 1
> [string]$b = $a
> $b
1
> $b.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object

所以一些类型被即时转换.根据大多数定义,这将使 PowerShell 成为弱类型语言.它肯定比例如更弱.Python(几乎?)从不即时转换类型.但可能不像 Perl 那样弱,它几乎可以根据需要转换任何东西.

So some types are converted on the fly. This will by most definitions make PowerShell a weakly typed language. It is certainly more weak than e.g. Python which (almost?) never convert types on the fly. But probably not at weak as Perl which will convert almost anything as needed.

这篇关于PowerShell 是强类型语言吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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