is,as,sizeof,typeof,GetType

  这几个符号说来也多多少少的用过,今天就根据ProC#的讲述来总结一下:
   IS:
   检查变量类型是否与指定类型相符,返回True ,False.不报错.
   老实说,我没怎么用过。看看下面的实例代码,很容易理解:
is,as,sizeof,typeof,GetType int i = 100;
is,as,sizeof,typeof,GetType
is,as,sizeof,typeof,GetType        
if (i is object)   //ture or false
        }
   但是,更经常的用法,在于判断一个未知类型(Object)是否与指定类型相符.
is,as,sizeof,typeof,GetTypestatic void Test(object o)
}
   而在这个时候,我经常用as来代替使用.
 AS:
  进行类型转换,如果不成功,返回null, 不报错.
is,as,sizeof,typeof,GetType  object o = "hi";
is,as,sizeof,typeof,GetType        
string s2 = o as string;
is,as,sizeof,typeof,GetType        
if (s2 != null)
        }
   而在实际的开发中,as 用的较多,通常在获得一个对象的时候,并不知道其类型,用此转换成功后才能使用,这一点倒和IS有几分相似的地方.
   应用一:
is,as,sizeof,typeof,GetType        DataSet ds = new DataSet();
is,as,sizeof,typeof,GetType        
//set values to ds here
is,as,sizeof,typeof,GetType
        Session["Data"= ds;
is,as,sizeof,typeof,GetType        DataSet ds2 
= Session["Data"as DataSet;
is,as,sizeof,typeof,GetType        
if (ds2 != null)
        }
    应用二:
is,as,sizeof,typeof,GetType        Button btn = form1.FindControl("btn"as Buttonl;
is,as,sizeof,typeof,GetType        
//Note: normally,here is GridView or others Data show Contorls
is,as,sizeof,typeof,GetType
        if (btn != null)
        }
   这个时候,用Is也可以达到目的
is,as,sizeof,typeof,GetType DataSet ds = new DataSet();
is,as,sizeof,typeof,GetType        
//set values to ds here
is,as,sizeof,typeof,GetType
        Session["Data"= ds;
is,as,sizeof,typeof,GetType        
if (Session["Data"is DataSet)
        }
  可空类型:
   比如int 是不能为null的,但是如果这样标识就可以:
is,as,sizeof,typeof,GetType  int? j = null;
is,as,sizeof,typeof,GetType Console.WriteLine(j);
  ??: 结合可空类型使用的符号, Format: a ?? b; 如果a 为null,则返回b的值,不然返回a的值.
       单要注意,a,b必须有一个为可空类型:
is,as,sizeof,typeof,GetType  int i = 22;
is,as,sizeof,typeof,GetType            
int m = 23;
is,as,sizeof,typeof,GetType            
int? n = 12;
is,as,sizeof,typeof,GetType           
// Console.WriteLine(i ?? m); //error
is,as,sizeof,typeof,GetType
            Console.WriteLine(j ?? m);   //output 23
is,as,sizeof,typeof,GetType
            Console.WriteLine(n ?? m);   //output 12
  Sizeof: 用于返回值类型在内存中占的大小,注意,只能是值类型,不能为引用类型:
is,as,sizeof,typeof,GetType Console.WriteLine(sizeof(byte)); //output 1
is,as,sizeof,typeof,GetType
            Console.WriteLine(sizeof(int));  //output 4
is,as,sizeof,typeof,GetType
            Console.WriteLine(sizeof(long)); //output 8
  typeof : 获得类型的System.Type 表示。
  GetType():如果要获得对象在运行时的类型,可以用此方法。
  应用:
is,as,sizeof,typeof,GetType            foreach (Control ctl in ctls.Controls)
            }
 typeof 在反射的时候,也有很大用途,随后学习到反射的时候再Demo.

相关文章:

  • 2021-08-25
  • 2021-06-04
  • 2021-05-16
  • 2021-06-09
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-12-11
  • 2022-01-20
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案