1.值类型转换
int a = 1; long b = 2;
隐式转换:b = a;
显示转换:a = (int)b;
当显示类型向隐式类型转换时,可能会出现溢出。为此,C#提供了checked和unchecked关键词用于决定是否捕获异常,也可以使用checked和unchecked语句。
---checked:捕获异常
---unchecked:放弃捕获异常
EG:checked关键字捕获异常实例:
Using System.Windows.Form;
try
{
a = checked(int)b;
}
catch(System.OverflowException)
{
MessageBox.show("隐式转换溢出异常");
return;
}
EG:checked语句捕获异常:
Using System.Windows.Form;
checked
{
a = (int)b;
}
catch(System.OverflowException)
{
MessageBox.show("隐式转换溢出异常");
return;
}
写代码是,将可能发生的非预期溢出的代码放到checked块中,将允许的溢出代码显示的放到unchecd块中。(告诉其他程序员异常是允许的)
在执行任何算术运算是,要求任何操作数为32位或者64位。当不够32位时,会自动转变到32位。
EG:
Byte b = 100;
b = b+100; //错误,这里必须显示转换,改位b = (Byte)(b+100);
b += 100; //不会出现异常
2.引用类型转换
CLR允许将一个对象强制转换成它的类型或者他的任何基类型。
eg:
class Fruit
{
}
class Apple:Fruit
{
public num = 1;
}
Fruit f = new Apple();
Type t = f.GetType();//t.FullName实际上是Apple类型,但是,不能直接范围Apple里面的字段
is操作符号:
---用于判断实例的类型,返回ture或者false(当实例为null,返回位false),不会抛出异常。
---由此,我们可以先进行类型判断,再进行类型转换。
---每次的类型转换都进行类型的检测,将降低运行的性能,由此,引入了as关键字。
eg:is关键字:
Console.WriteLine(f is Fruit); //ture
Console.WriteLine(f is Apple); //false
if(f is Apple) //类型判断
{
Console.WriteLine(f.num); //类型判断
}
eg:as关键字
Fruit f = new Fruit();
Apple a = f as Apple; // 类型判断,如果可以转换则进行转换,否则返回null
if(a != null)
Console.WriteLine(a.num);
EG:在一个Form上推拽不同类型的控件:如button,lablel,box,现在要选择其中的button,将他们的名字改为kkk
foreach(Control c in this.Controls) //访问所有的控件
{
button c1 = c as button; //转换位button类型。
if(c1 != null)
c1.Text = "kkk";
}
说明:所有的控件都是从control类继承