当前位置:编程学习 > C#/ASP.NET >>

C# 运算符

1、条件运算符
 
条件运算符(?:)也称为三元(目)运算符,是if...else结构的简化形式,可以嵌套使用。
 
[csharp] 
int x = 1;  
string s = x + ""; ;  
s += (x == 1 ? "man" : "men");  
Console.WriteLine(s);//输出1man  
2、checked和unchecked
 
[csharp]  
byte b = 255;  
{  
    b++;  
}  
Console.WriteLine(b.ToString());//输出0  
但是由于byte只能包含0-255的数,所以++之后会导致b溢出。因此,如果把一个代码块标记为checked,CLR就会执行溢出检查,如果发生溢出,就抛出来OverflowException异常。
如下所示:
[csharp]  
byte b = 255;  
checked  
{  
    b++;  
}  
Console.WriteLine(b.ToString());//抛出OverflowException异常,算术运算导致溢出  
如果要禁止溢出检查,可以标记为unchecked:
[csharp] 
byte b = 255;  
unchecked  
{  
    b++;  
}  
Console.WriteLine(b.ToString());//输出0,不抛异常  
3、is
 
is运算符可以检查对象是否与特定的类型兼容。“兼容”表示对象是该类型或者派生自该类型。
 
[csharp] 
string i = "hello i...";  
if (i is object)  
{  
    Console.WriteLine("i is an object...");//执行了这句话  
}  
4、as
 
as运算符用于执行引用类型的显式类型转换(string 为引用类型)。如果要转换的类型与指定的类型兼容,转换就会成功进行;如果类型不兼容,as运算符就会返回Null。
 
[csharp]  
string i = "hello i...";  
if (i is object)  
{  
    object obj = i as object;//显式类型转换  
    Console.WriteLine(obj is string ? "obj is string..." : "obj is not string...");//输出obj is string...  
}  
5、sizeof
 
sizeof运算符可以确定stack中值类型需要的长度(单位是字节):
 
[csharp]  
int byteSize = sizeof(byte);//输出1  
int charSize = sizeof(char);//输出2  
int uintSize = sizeof(uint);//输出4  
int intSize = sizeof(int);//输出4  
6、typeof
 
typeof运算符常常会跟GetType()方法结合使用,来反射出类的属性、方法等。
 
[csharp]  
Type intType = typeof(int);  
System.Reflection.MethodInfo[] methodInfo = intType.GetMethods();  
methodInfo.ToList().ForEach(x => Console.WriteLine(x.Name));//反射出int类型的方法名  
7、可空类型和运算符
 
如果其中一个操作数或两个操作数都是null,其结果就是null,如:
 
[csharp]  
int? a = null;  
int? b = a + 4;//b = null  
int? c = a * 5;//c = null  
但是在比较可空类型时,只要有一个操作数为null,比较的结果就是false。但不能因为一个条件是false,就认为该条件的对立面是true。如:
[csharp]  
int? a = null;  
int? b = -5;  
  
if (a >= b)  
    Console.WriteLine("a > = b");  
else  
    Console.WriteLine("a < b");//会输出这句话  
8、空合并运算符
例如:
 
[csharp]  
int? a = null;//加问号,是为了能够给Int型赋值为null  
int b;  
b = a ?? 1;  
[csharp]  
Console.WriteLine(b);//输出1  
a = 3;  
b = a ?? 10;  
Console.WriteLine(b);//输出10  
 
补充:软件开发 , C# ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,