is and as
来源:互联网 发布:怎么在淘宝买av种子 编辑:程序博客网 时间:2024/04/27 21:10
本文将介绍以下内容:
• 类型转换
• is/as操作符小议
1. 引言
类型安全是.NET设计之初重点考虑的内容之一,对于程序设计者来说,完全把握系统数据的类型安全,经常是力不从心的问题。现在,这一切已经在微软大牛们的设计框架中为你解决了。在.NET中,一切类型都必须集成自System.Object类型,因此我们可以很容易的获得对象的准确类型,方法是:GetType()方法。那么.NET中的类型转换,应该考虑的地方有那些呢?
2. 概念引入
类型转换包括显示转换和隐式转换,在.NET中类型转换的基本规则如下:
- 任何类型都可以安全的转换为其基类类型,可以由隐式转换来完成;
- 任何类型转换为其派生类型时,必须进行显示转换,转换的规则是:(类型名)对象名;
- 使用GetType可以取得任何对象的精确类型;
- 基本类型可以使用Covert类实现类型转换;
- 除了string以外的其他类型都有Parse方法,用于将字符串类型转换为对应的基本类型;
- 值类型和引用类型的转换机制称为装箱(boxing)和拆箱(unboxing)。
3. 原理与示例说明
浅谈了类型转换的几个普遍关注的方面,该将主要精力放在is、as操作符的恩怨情仇上了。类型转换将是个较大的话题,留于适当的时机讨论。
is/as操作符,是C#中用于类型转换的,提供了对类型兼容性的判断,从而使得类型转换控制在安全的范畴,提供了灵活的类型转换控制。
is的规则如下:
- 检查对象类型的兼容性,并返回结果,true或者false;
- 不会抛出异常;
- 如果对象为null,则返回值永远为false。
其典型用法为:
1object o = new object();
2
3class A
4
5{
6
7}
8
9if (o is A) //执行第一次类型兼容检查
10
11{
12
13 A a = (A) o; //执行第二次类型兼容检查
14
15}
16
17
2
3class A
4
5{
6
7}
8
9if (o is A) //执行第一次类型兼容检查
10
11{
12
13 A a = (A) o; //执行第二次类型兼容检查
14
15}
16
17
as的规则如下:
- 检查对象类型的兼容性,并返回结果,如果不兼容就返回null;
- 不会抛出异常;
- 如果结果判断为空,则强制执行类型转换将抛出NullReferenceException异常。
其典型用法为:
1object o = new object();
2
3class B
4
5{
6
7}
8
9B b = o as B; //执行一次类型兼容检查
10
11if (b != null)
12
13{
14
15 MessageBox.Show("b is B's instance.");
16
17}
18
19
2
3class B
4
5{
6
7}
8
9B b = o as B; //执行一次类型兼容检查
10
11if (b != null)
12
13{
14
15 MessageBox.Show("b is B's instance.");
16
17}
18
19
4. 结论
纵上比较,is/as操作符,提供了更加灵活的类型转型方式,但是as操作符在执行效率上更胜一筹,我们在实际的编程中应该体会其异同,酌情量才。
- is and as
- as-is and to-be
- Glory is as ephemeral as smoke and clouds
- is as
- Struct is the same as int and float
- 表 is marked as crashed and should be repaired
- mysql错误:is marked as crashed and should be repaired
- Table 'table_name' is marked as crashed and should be repaired
- Table is marked as crashed and should be repaire 解决方法
- is marked as crashed and should be repaired
- mysql错误is marked as crashed and should be repaired
- Table 'xxxxxxx' is marked as crashed and should be repaired
- Table ‘xxx’ is marked as crashed and should be repaired ...
- table_name' is marked as crashed and last (automatic?) repair failed
- Table is marked as crashed and should be repaire
- Table is marked as crashed and should be repaire (
- linux Table is marked as crashed and should be repaired
- 解决“is marked as crashed and should be repaired”
- 【Java编程试题】程序1 TestRabbit.java
- awk使用手册
- window.open详解
- JAVA群发邮件代码
- java 数字处理工具类
- is and as
- java中使用redis
- js 合并 数组,并去除重复的内容
- WinCE6.0 Platform Builder180天过期破解方法
- 毒啊
- 如何安装SQL Server 2008 Express
- Qualcomm摄像头模块中的一些数据结构
- Windows 7 x64的Apache + PHP的配置方法以及问题解决
- C#-Server.MapPath()