AS和IS对于如何安全的“向下转型”提供了较好的解决方案,因此我们有两种转型的选择:
1、使用AS运算符进行类型转换
2、先使用IS运算符判断类型是否可以转换,再使用()运算符进行显示的转换
先说AS运算符:
AS运算符用于在两个应用类型之间进行转换,如果转换失败则返回null,并不抛出异常,因此转换是否成功可以通过结果是否为null进行判断,并且只有在运行时才能判断。AS运算符有一定的适用范围,他只适用于引用类型或可以为null的类型。
IS运算符:
IS运算符用于检查对象是否与给定类型兼容,并不进行实际的转换。如果判断对象引用为null,则返回false。由于仅仅判断是否兼容,因此不会抛出异常。使用范围,只适用于引用类型转换、装箱转换和拆箱转换,而不支持值类型转换。
在实际工作中尽量使用AS运算符,而少使用()运算符的显示转换的理由:
1、无论是AS和IS运算符,都比世界使用()运算符强制转换更安全。
2、不会抛出异常,免除使用try···catch进行异常捕获的必要和系统开销,只需要判断是否为null。
3、使用AS比使用IS性能更好(C#4.0权威指南上这么说),验证结果如下:第一次运行时有AS时间更短(没有截图),但是多运行几次之后,结果如图。
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace book
{
class Class1 { }
class Program
{
private Class1 c1 = new Class1();
static void Main(string[] args)
{
Program program = new Program();
Stopwatch timer = new Stopwatch();
timer.Start();
for(int i = 0; i < 100000; i++)
{
program.Dosomething1();
}
timer.Stop();
decimal micro = timer.Elapsed.Ticks / 10m;
Console.WriteLine("IS运算100000次所需时间,{0:F1}微秒",micro);
timer = new Stopwatch();
timer.Start();
for(int i = 0; i < 100000; i++)
{
program.Dosomething2();
}
timer.Stop();
micro = timer.Elapsed.Ticks/10m;
Console.WriteLine("AS运算100000次所需时间,{0:F1}微秒",micro);
Console.ReadKey();
}
public void Dosomething1()
{
object c2 = c1;
if(c2 is Class1)
{
Class1 c = (Class1)c2;
}
}
public void Dosomething2()
{
object c2 = c1;
Class1 c = c2 as Class1;
if (c != null)
{
}
}
}
}
第三次
第四次