什么是类型安全的.net?(What is type

编程入门 行业动态 更新时间:2024-10-25 12:26:21
什么是类型安全的.net?(What is type-safe in .net?)

什么是类型安全?

这是什么意思,为什么这很重要?

What is type-safe?

What does it mean and why is it important?

最满意答案

如果你问“ 一般安全”这个概念是什么意思,代码的特征就是允许开发人员确定一个值或者对象会显示某些属性(即某种类型的属性),以便他/她可以以特定的方式使用它,而不用担心意外或未定义的行为。

例如,在C#中,您可以说ArrayList类不是类型安全的,因为它可以存储任何对象 ,这意味着您可以执行以下操作:

var integers = new ArrayList(); integers.Add(1); integers.Add(2); integers.Add("3"); for (int i = 0; i < integers.Count; ++i) { int integer = (int)integers[i]; // do something }

上述将编译,因为String从String派生(如Int32 ),因为值“3”即使它是一个字符串而不是一个整数,可以合法添加到ArrayList 。 但是,当您尝试将integer设置为(int)integers[2]时,它将抛出InvalidCastException ,因为无法将String转换为Int32 。

另一方面, List<T>类类型安全的完全相反的原因 - 即如果integers是List<int> ,上面的代码将不会被编译。 您可以确定开发人员从类型安全的List<int>访问的任何值都是int (或任何相应的T用于任何通用List<T> ); 因此,您可以确保您可以执行诸如转换为int (显然)或者说long 。

If you're asking what the idea of "type-safe" in general means, it's the characteristic of code that allows the developer to be certain that a value or object will exhibit certain properties (i.e., be of a certain type) so that he/she can use it in a specific way without fear of unexpected or undefined behavior.

For instance, in C#, you could say the ArrayList class is not type-safe because it can store any object, which means you can do something like the following:

var integers = new ArrayList(); integers.Add(1); integers.Add(2); integers.Add("3"); for (int i = 0; i < integers.Count; ++i) { int integer = (int)integers[i]; // do something }

The above will compile because the value "3", even though it's a string and not an integer, can legally be added to an ArrayList since String derives (like Int32) from Object. However, it will throw an InvalidCastException when you try to set integer to (int)integers[2] because a String cannot be cast to an Int32.

On the other hand, the List<T> class is type-safe for exactly the opposite reason--i.e., the above code would not compile if integers were a List<int>. Any value that you the developer access from within a type-safe List<int> you can be certain is an int (or whatever the corresponding T is for any generic List<T>); and you can therefore be sure that you'll be able to perform operations such as casting to int (obviously) or, say, long.

更多推荐

本文发布于:2023-08-06 03:16:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1444419.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   net   type

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!