C#基础类型 类型转换

 class Preson
{
public int i = 30;
public int n = 40;
public int add(int a, int b)
{
return a + b;
}

}

class Water : Preson
{
public int cut(int b, int c)
{
return b - c;
}

}
   class Program
{
static void Main(string[] args)
{
Preson p = new Water();//可以转换到父类型
p.add(2,4);
       Water s =(Water)new Preson();//编译能通过,运行时出错,不能把父类型转换到子类型。InvalidCastException错误
Water w = new Water();//转换后能访问父类的所有共有方法,字段,属性。
       w.cut(2, 3);
       bool isbol = (w is Preson);//is操作符返回bool值。不会抛出异常。这里返回true      

        Preson pp = new Preson();
        bool isbol = (pp is Water);//这里就不行

            Preson pr = w as Preson;//clr核实w是否是兼容于preson类型,如果是会返回一个非null的同一个对象的引用。 否者返回null,as操作符的工作方式和强制类型转换一样,只是它不会抛出异常,如果对象不能转换,结果就是null。

}
}
posted @ 2011-11-18 14:40  Rookier  阅读(149)  评论(0编辑  收藏  举报