现在的位置: 首页 > 综合 > 正文

is,as,sizeof,typeof,GetType

2012年02月12日 ⁄ 综合 ⁄ 共 2269字 ⁄ 字号 评论关闭

is,as,sizeof,typeof,GetType

   这几个符号说来也多多少少的用过,今天就根据ProC#的讲述来总结一下:
   IS:
   检查变量类型是否与指定类型相符,返回True ,False.不报错.
   老实说,我没怎么用过。看看下面的实例代码,很容易理解:
 int i = 100;

        
if (i is object)   //ture or false
        {
            Response.Write(
"i is object</br>");
        }

   但是,更经常的用法,在于判断一个未知类型(Object)是否与指定类型相符.

static void Test(object o)
    
{
        Class1 a;
        Class2 b;

        
if (o is Class1)
        
{
            Console.WriteLine(
"o is Class1");
            a 
= (Class1)o;
            
// Do something with "a."
        }

}

   而在这个时候,我经常用as来代替使用.
 AS:
  进行类型转换,如果不成功,返回null, 不报错.

  object o = "hi";
        
string s2 = o as string;
        
if (s2 != null)
        
{
            Response.Write(
"ok</br>");
        }

   而在实际的开发中,as 用的较多,通常在获得一个对象的时候,并不知道其类型,用此转换成功后才能使用,这一点倒和IS有几分相似的地方.
   应用一:

        DataSet ds = new DataSet();
        
//set values to ds here
        Session["Data"= ds;
        DataSet ds2 
= Session["Data"as DataSet;
        
if (ds2 != null)
        
{
            
//code here
        }

    应用二:

        Button btn = form1.FindControl("btn"as Buttonl;
        
//Note: normally,here is GridView or others Data show Contorls
        if (btn != null)
        
{
            
//code here
        }

   这个时候,用Is也可以达到目的

 DataSet ds = new DataSet();
        
//set values to ds here
        Session["Data"= ds;
        
if (Session["Data"is DataSet)
        
{
            Response.Write(
"ok");
        }

  可空类型:
   比如int 是不能为null的,但是如果这样标识就可以:

  int? j = null;
 Console.WriteLine(j);

  ??: 结合可空类型使用的符号, Format: a ?? b; 如果a 为null,则返回b的值,不然返回a的值.
       单要注意,a,b必须有一个为可空类型:

  int i = 22;
            
int m = 23;
            
int? n = 12;
           
// Console.WriteLine(i ?? m); //error
            Console.WriteLine(j ?? m);   //output 23
            Console.WriteLine(n ?? m);   //output 12

  Sizeof: 用于返回值类型在内存中占的大小,注意,只能是值类型,不能为引用类型:

 Console.WriteLine(sizeof(byte)); //output 1
            Console.WriteLine(sizeof(int));  //output 4
            Console.WriteLine(sizeof(long)); //output 8

  typeof : 获得类型的System.Type 表示。
  GetType():如果要获得对象在运行时的类型,可以用此方法。
  应用:

            foreach (Control ctl in ctls.Controls)
            
{
                
if (ctl.GetType() == typeof(TextBox))
                
{
                    TextBox c 
= ctl as TextBox;
                    c.Text 
= "";
                }

            }

 typeof 在反射的时候,也有很大用途,随后学习到反射的时候再Demo.

抱歉!评论已关闭.