C# is as

if(obj is ClassA) //遍历类层次,看OBJ是不是ClassA类型
{
    ClassA a=(ClassA) obj; //遍历类层次,看obj能否转换为ClassA,不成功则抛出异常
   ...
 }
//作了两次类层次遍历

ClassA a = obj as ClassA //不成功返回null,不会抛出异常
If(a)
{

}
//仅作了 一次类层次遍历

using System.Runtime.InteropServices;
using System;
delegate string DTE(int x, string s);

class MYTestX
{
    class CO
    {

    }
    class CTEST : CO
    {

    }
    class CDT : CO
    {

    }
    static void Main(string[] args)
    {

        CTEST ot = new CTEST();
        CO odt = new CDT();
        ot = (CTEST)odt; //抛出异常
        ot = odt as CTEST;//不会抛出异常,ot = null

        CTEST ot1 = new CTEST();
        CDT odt1 = new CDT();
        ot1 = odt1; //编译错误,不能执行类型转换
 
        Console.WriteLine( ot == null ? "null" : ot.ToString());

    }

}

 

      

    

  

  

  

  

  

  

  

  

  

  

  

posted @ 2016-10-01 18:46  时空观察者9号  阅读(194)  评论(0编辑  收藏  举报