您的位置:首页 > 其它

is,as,sizeof,typeof,GetType

2008-09-19 13:18 288 查看

is,as,sizeof,typeof,GetType

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

int i = 100;

if (i is object) //ture or false
static void Test(object o)
object o = "hi";
string s2 = o as string;
if (s2 != null)
DataSet ds = new DataSet();
//set values to ds here
Session["Data"] = ds;
DataSet ds2 = Session["Data"] as DataSet;
if (ds2 != null)
Button btn = form1.FindControl("btn") as Buttonl;
//Note: normally,here is GridView or others Data show Contorls
if (btn != null)
DataSet ds = new DataSet();
//set values to ds here
Session["Data"] = ds;
if (Session["Data"] is DataSet)
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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: