什么是类型安全的。NET? [英] What is type-safe in .net?

查看:127
本文介绍了什么是类型安全的。NET?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是类型安全的?

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

What does it mean and why is it important?

推荐答案

如果你问类型安全中的一般的想法的意思,它是code特点它允许开发人员可以肯定,一个值或对象会表现出某些特性(即是某种类型的),这样​​他/她可以以特定的方式使用它,而不用担心意外的或不确定的行为。

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.

例如,在C#中,你可以说,的ArrayList 类的<​​em>没有的类型安全的,因为它可以存储的任何对象,这意味着你可以做类似如下:

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
}

以上将编译,因为值3,尽管它是一个字符串,而不是一个整数,可以依法将其添加到的ArrayList ,因为字符串提炼出来(如的Int32 )从对象。但是,它会抛出一个 InvalidCastException的,当您尝试设置整数(INT)整数[2] ,因为字符串不可能的铸造的到的Int32

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.

在另一方面,在名单,其中,T&GT; 类的<​​em>是的类型安全的完全相反的原因 - 即高于$ C $Ç会的不可以编译如果整数是一个名单,其中,INT&GT; 。任何值,你从内部开发人员能够访问一个类型安全的名单,其中,INT&GT; 您可以某些 INT (或其他相应的 T 为任何普通的名单,其中,T&GT; );你因此可以肯定,你就可以进行操作,如铸造 INT (明显),或者说,

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.

这篇关于什么是类型安全的。NET?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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