做“类型安全"和“强类型"意思是一样的? [英] Do "type-safe" and "strongly typed" mean the same thing?

查看:26
本文介绍了做“类型安全"和“强类型"意思是一样的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类型安全"和强类型"是同一个意思吗?

解决方案

不,不一定 - 尽管这取决于您对术语的定义,并且没有非常明确且被广泛接受的定义.

例如,动态编程语言通常是类型安全的,但不是强类型的.换句话说,没有编译时类型信息来确定您可以对类型做什么和不能做什么,但在执行时,运行时会确保您不会像使用另一种类型一样使用一种类型.

例如,在 C# 4.0 中,您可以:

dynamic foo = "hello";动态长度 = foo.Length;//在执行时使用 String.Lengthfoo = new int[] { 10, 20, 30 };长度 = foo.Length;//在执行时使用 Array.Length动态栏 = (FileStream) foo;//失败!

最后一行是类型安全的关键:没有从 int 数组到 FileStream 的安全转换,因此操作失败 - 而不是处理数组对象的字节 就好像它们是一个 FileStream.

C# 通常既是强类型"(作为一种语言)又是类型安全的:编译器不会让您尝试对对象进行任意调用,并且运行时不会让您执行不适当的转换.

我不完全确定不安全代码适用于何处 - 恐怕我对此知之甚少,无法发表评论.

C# 4 中的动态类型允许弱类型但仍然是类型安全的代码,如上所示.

请注意,foreach 执行隐式转换,使其成为一种混合:

ArrayList list = new ArrayList();list.Add("foo");foreach(列表中的文件流流){...}

这将编译(最近有另一个问题)但在执行时会失败.具有讽刺意味的是,这是因为您试图stream 变量进行强类型化,这意味着您必须对迭代器的结果执行强制转换.>

Do "type-safe" and "strongly typed" mean the same thing?

解决方案

No, not necessarily - although it depends on your definition of the terms, and there are no very clear and widely accepted definitions.

For instance, dynamic programming languages are often type safe, but not strongly typed. In other words, there's no compile-time type information determining what you can and can't do with a type, but at execution time the runtime makes sure you don't use one type as if it were another.

For example, in C# 4.0, you can do:

dynamic foo = "hello";
dynamic length = foo.Length; // Uses String.Length at execution time
foo = new int[] { 10, 20, 30 };
length = foo.Length; // Uses Array.Length at execution time
dynamic bar = (FileStream) foo; // Fails!

The last line is the key to it being type-safe: there's no safe conversion from an int array to a FileStream, so the operation fails - instead of treating the bytes of the array object as if they were a FileStream.

EDIT: C# is normally both "strongly typed" (as a language) and type safe: the compiler won't let you attempt to make arbitrary calls on an object, and the runtime won't let you perform inappropriate conversions.

I'm not entirely sure where unsafe code fits in - I don't know enough about it to comment, I'm afraid.

Dynamic typing in C# 4 allows weakly typed but still type-safe code, as shown above.

Note that foreach performs an implicit conversion, making it a sort of hybrid:

ArrayList list = new ArrayList();
list.Add("foo");

foreach (FileStream stream in list)
{
    ...
}

This will compile (there was another question on this recently) but will fail at execution time. Ironically, that's because you're trying to be strongly typed with respect to the stream variable, which means you have to perform a cast on the result of the iterator.

这篇关于做“类型安全"和“强类型"意思是一样的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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