一、类型转换
**************************************************************************************************************
1.任何类型都可以转换为其基类类型,用隐式转换完成;
2.任何类型转换为其派生类型时,必须进行显示转换。如:(类型名)对象名;
3.使用GetType可以取得任何对象的精确类型;
4.基本类型可以使用Convert类实现类型转换;
5.除了string以外的其他类型都有Parse方法,用于将字符串类型转换成对应的基本类型;
6.值类型和引用类型的转换称为装箱(boxing)或拆箱(unboxing);
**************************************************************************************************************
二、is/as示例
在实际工作中尽量使用AS运算符,而少使用()运算符的显示转换的理由:
1、无论是AS和IS运算符,都比世界使用()运算符强制转换更安全。
2、不会抛出异常,免除使用try···catch进行异常捕获的必要和系统开销,只需要判断是否为null。
is转换规则:
1. 检查对象类型的兼容性,并返回结果true(false);
2.不会抛出异常;
3.如果对象为null,刚返回false;
示例:
object o = "abc";
if (o is string) //执行第一次类型兼容性检查
{
string s = (string)o; //执行第二次类型兼容性检查,并转换
MessageBox.Show("转换成功!");
}
else
{
MessageBox.Show("转换失败!");
}
as转换规则:
1.检查对象类型的兼容性,并返回转换结果,如果不兼容则返回null;
2.不会抛出异常;
3.如果结果判断为空,则强制执行类型转换将抛出NullReferenceException异常;
示例:
object o = "abc";
string s = o as string; //执行第一次类型兼容性检查,并返回结果
if (s != null)
MessageBox.Show("转换成功!");
else
MessageBox.Show("转换失败!");
注:as比is少执行一次兼容性检查,性能可能会高一点点。
测试100000次,对于值类型,is>as;对于引用类型,as>is
class TestClass
{
}
class Program
{
static Stopwatch sw_Timer = new Stopwatch();
const int NUM = 100000;
static int? TestIntType;
static TestClass testClass = new TestClass();
static void Main()
{
Console.WriteLine("值类型测试.");
sw_Timer.Restart();
for (int i = 0; i < NUM; i++)
{
object obj1 = i + 1;
if (obj1 is int)
{
TestIntType = (int?)obj1;
}
}
sw_Timer.Stop();
Console.WriteLine("Is运算{0}次所需时间,{1}Ticks.", NUM, sw_Timer.ElapsedTicks);
sw_Timer.Restart();
for (int i = 0; i < NUM; i++)
{
object obj2 = i + 1;
TestIntType = obj2 as int?;
if (TestIntType != null)
{
}
}
sw_Timer.Stop();
Console.WriteLine("As运算{0}次所需时间,{1}Ticks.", NUM, sw_Timer.ElapsedTicks);
Console.WriteLine("引用类型测试.");
sw_Timer.Restart();
for (int i = 0; i < NUM; i++)
{
object obj3 = testClass;
if (obj3 is TestClass)
{
TestClass obj4 = (TestClass)obj3;
}
}
sw_Timer.Stop();
Console.WriteLine("Is运算{0}次所需时间,{1}Ticks.", NUM, sw_Timer.ElapsedTicks);
sw_Timer.Restart();
for (int i = 0; i < NUM; i++)
{
object obj5 = testClass;
TestClass obj6 = obj5 as TestClass;
if (obj6 != null)
{
}
}
sw_Timer.Stop();
Console.WriteLine("As运算{0}次所需时间,{1}Ticks.", NUM, sw_Timer.ElapsedTicks);
Console.ReadKey();
}
}
---------------------
本文来自 njit_77 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/njit_77/article/details/78168812?utm_source=copy