类型转换 笔记

隐式转换  可以将子类赋值给基类

int
a=5; //system.Int32
long b; //System.Int 64
// a=b; // 编译出错,缺少强制转换,因为b存储的最大值大于a
try
{
a
=checked(int)b; //显示转换
}
catch
{

}
b
=a; //隐式转换
Console.WriteLine(b);

Byte b
=100;
b
=(Byte)(b+100);
// b+=100 这里的b不需要显示转换
Console.WriteLine(b);


class Fruit
{

}
class Apple:Frutuit
{
pulic
int i=1;
}
class Conversions
{
Fruit f
=new Apple();
//Console.WriteLine(f.i); // 编译出错
//1
if(f is Apple)
{
Apple a
=(Apple) f; //需要显示转换f
Console.WriteLine(a.i);
}
//2
Fruit f=new Apple();
Apple a
=f as Apple;
if(a!=null)
{
Console.WriteLine(a.i);
}

}
posted @ 2011-08-16 12:16  尐肥羊  阅读(133)  评论(0编辑  收藏  举报
up