#region 取余运算符%:返回除运算的余数
int i = 5 % 2;
Console.WriteLine(i); //返回1
#endregion
#region checked和unchecked运算符 :把代码块标记为checked,会执行溢出检查,如果溢出就报异常
//没有check的情况
byte b = 255; //byte的取值范围是0-255
b++;
//Console.WriteLine(b); //返回0
Console.WriteLine(b.ToString()); //返回0
Console.ReadKey();
//有checked的情况
byte a = 255; //byte的取值范围是0-255
//checked
//{
// a++; //在这里报异常
//}
unchecked
{
a++;//不报异常,返回零;默认状态下为unchecked
}
Console.WriteLine(a.ToString()); //返回0
Console.ReadKey();
#endregion
#region is运算符:检查对象是否与特定的类型兼容
int j = 10;
if (j is object)
{
Console.WriteLine("j和object兼容"); //j和object兼容 object是所有类型的基类
}
if(j is String)
{
Console.WriteLine("j和string兼容"); //j和string不兼容
}
#endregion
#region as运算符:用于执行引用类型的显式类型转换,如果要转换的类型与指定的类型兼容,则转换成功;否则返回null值
object o1 = "string";
object o2 = 5;
string s1 = o1 as string; //s1的值为string
string s2 = o2 as string; //s2的值为null
// int s3 = o2 as int; //报错:as 运算符必须用于引用类型或可以为 null 的类型(“int”是一种不可以为 null 值的类型)
List<string> s4 = o1 as List<string>; //null值
#endregion
#region sizeof运算符:确定堆栈中值类型需要的长度(单位是字节);注意:只能在不安全的代码中使用sizeof运算符
Console.WriteLine(sizeof(int)); //显示为4,因为int有4个字节
//unsafe
//{
// Console.WriteLine(sizeof(int));//报错:不安全代码会在使用/unsage编译的情况下出现
//}
#endregion
#region typeof运算符:返回一个表示特定类型的System.Type对象;在反射中非常有用
System.Type type = typeof(string);//返回诸如:{Name = "String" FullName = "System.String"}的信息
#endregion
#region 可空类型和运算符
int? t=null;
int? o=t+4;//o=null;
#endregion
#region 空接合运算符(??):如果第一个数为null,返回第二个数;否则返回第一个数
//第一个操作数为可空类型或引用类型,第二个操作数与第一个操作类型相同或者可以隐式转换为第一个操作数
int? e=null;
int q;
q=e??10; //q=10
e=3;
q=e??10; //e=3
#endregion