9.[] 运算符 方括号 ([]) 用于数组、索引器和属性,也可用于指针。 type [] array [ indexexpr ] 其中: type 类型。 array 数组。 indexexpr 索引表达式 10.() 运算符 除了用于指定表达式中运算符的顺序外,圆括号还用于指定转换(类型转换) ( type ) expr 其中:type expr 要转换为的类型名。 expr 一个表达式。转换显式调用从 expr 类型到 type 类型的转换运算符;如果未定义这样的转换运算符,则该转换将失败。 12.自增自减操作符 自增操作符++对变量的值加1,而自减操作符--对变量的值减1。此操作符有前后缀之分。对于前缀操作符,遵循的原则是“先增减,后使用”,而后缀操作符则正好相反,是“先使用,后增减” using System; class MikeCat { public static void Main() { double x,y; x=1.5; Console.WriteLine(++x);//自增后等于2.5 y=1.5; Console.WriteLine(y++);//先显示1.5后自增 Console.WriteLine(y);//自增后等于2.5 } } 13.as 运算符 as 运算符用于执行可兼容类型之间的转换。as 运算符用在以下形式的表达式中:expression as type 其中: expression 引用类型的表达式。type 引用类型。 as 运算符类似于类型转换,所不同的是,当转换失败时,as 运算符将产生空,而不是引发异常。在形式上,这种形式的表达式: expression as type 等效于: expression is type ? (type)expression : (type)null 只是 expression 只被计算一次。 请注意,as 运算符只执行引用转换和装箱转换。as 运算符无法执行其他转换,如用户定义的转换,这类转换应使用 cast 表达式来代替其执行。 using System; class MyClass1 { } class MyClass2 { } public class IsTest { public static void Main() { object [] myObjects = new object[6]; myObjects[0] = new MyClass1(); myObjects[1] = new MyClass2(); myObjects[2] = "hello"; myObjects[3] = 123; myObjects[4] = 123.4; myObjects[5] = null; for (int i=0; i<myObjects.Length; ++i) { string s = myObjects[i] as string; Console.Write ("{0}:", i); if (s != null) Console.WriteLine ( "'" + s + "'" ); else Console.WriteLine ( "not a string" ); } } } 输出 0:not a string 1:not a string 2:'hello' 3:not a string 4:not a string 5:not a string 14.new 操作符 new操作符用于创建一个新的类型实例,有三种形式: A:对象创建表达式,用于创建一个类类型或值类型的实例。 B:数组创建表达式,用于创建一个数组类型实例。 C:委托创建表达式,用于创建一个新的委托类型实例。 15.typeof操作符 typeof操作符用于获得系统原型对象的类型。 using System; class MikeCat { public static void Main() { Console.WriteLine(typeof(int)); Console.WriteLine(typeof(System.Int32)); } }//结果:System.Int32 System.Int32 //表明int和System.Int32是同一个类型 c#中用GetType()方法获得一个表达式在运行时的类型 using System; class MikeCat { public static void Main() { int r=3; Console.WriteLine("圆的面积等于{0}",r*r*Math.PI); Console.WriteLine("类型是{0}",(r*r*Math.PI).GetType()); } }//圆的面积等于28.2743338823081 //类型是System.Double 16.sizeof操作符 sizeof操作符获得一个值类型的字节大小 using System; class MikeCat { unsafe public static void SizesOf() { Console.WriteLine("short的大小是{0}",sizeof(short)); Console.WriteLine("int的大小是{0}",sizeof(int)); Console.WriteLine("long的大小是{0}",sizeof(long)); } public static void Main() { SizesOf(); } }//short 的大小是2;int的大小是4;long的大小是8; 17.checked和unchecked操作符 在进行整型算术运算或从一种整型显示转换到另外一种整型时,有可能产生溢出。 检查这种溢出c#中有两种处理方式: 第一:在编译时设置溢出校验选项(溢出校验默认是禁用的): csc /checked test.cs //这个我们在前面有所介绍 第二:使用checked和unchecked操作符来确定是否进行溢出校验。即使编译时禁用溢出校验,计算时也同样引发异常。 using System; class MikeCat { public static void Main(string[] args) { long factorial=1; long num=Int64.Parse(args[0]); for(long cur=1;cur<=num;cur++) { checked{factorial*=cur;} } Console.WriteLine("{0}的阶乘是{1}",num,factorial); } }//test.exe 3 3的阶乘是6 unchecked操作符与checked操作符正好相反,即使溢出,被unchecked操作符所括住的代码也不会引发异常。 各个操作符的优先级我就不在这里多说了。主要是手累。呵呵。仍然和以前c++的优先级相似。详细可参看MSDN。感谢大家关注本教程,欢迎访问老
|