关于:C# 与 Java 的不同点总结(C#的特点):
1.@
在字符窜前面加上@可使字符窜中的转义符失效。可尝试实行如下代码:
- string aaa = @"C:\\tmp\\aaa.txt";
- Console.WriteLine(aaa);
- aaa = "C:\\tmp\\aaa.txt";
- Console.WriteLine(aaa);
2.?可空类型和运算符
定义数据类型时可使用?以表示该数据库性允许为null。例如:
- int? a = null;
- Console.WriteLine(a);
3.is运算符
判断类型是否兼容,相当于java的instanceof关键字。
4.sealed关键字
相当于java的final,表示类或方法不可继承(密封)。
5.virtual关键字
表示该方法或该属性能够被重写。在java中默认情况下所有方法和属性都能被重写。
6.部分类关键字partial
允许类,结构或接口放入多个文件中。
- //TheBigClass1.cs
- partial class TheBigClass
- {
- public void MethodOne()
- {
- }
- }
- //TheBigClass2.cs
- partial class TheBigClass
- {
- public void MethodTwo()
- {
- }
- }
7.结构:struct
- struct Dimensions
- {
- public double Length;
- public double Width;
- }
8.只读字段readonly。
和定义常量字段的coust的区别是,readonly字段允许在类的构造函数中进行初始化(静态构造函数中也可以初始化)。
9.静态构造函数
- class MyClass
- {
- public static string value;
- //静态构造函数
- static MyClass()
- {
- //首次加载类时运行,只执行一次
- value = "A";
- }
- //实例构造函数
- private MyClass()
- {
- //每次创建类的实例时执行
- value = "B";
- }
- static void Main(string[] args)
- {
- Console.WriteLine(value);//A
- MyClass clz = new MyClass();
- Console.WriteLine(value);//B
- }
- }
10.out关键字
允许函数从一个例程中输出多个值。
请注意,使用out关键字时,变量是通过引用传值的。所以在从被调用的方法返回时,方法对该变量的任何修改都会被保留下来。
- static void Main(string[] args)
- {
- int i;
- initInt(out i);
- Console.WriteLine(i);
- }
- static void initInt(out int i) {
- i = 100;
- }
11.ref参数实现
给方法传递参数时的引用传值。(通过值传递变量是默认的)
- static void initInts(int[] ints, ref int i)
- {
- ints[0] = 200;
- i = 300;
- }
在调用方法时对应的字段也要加上ref关键字
initInts(ints, ref i)
注意:使用引用传值,该方法对变量的任何改变都会影响原来对象的值。
12.as运算符
判断类型是否兼容,不兼容返回null.
- class MyClass
- {
- static void Main(string[] args)
- {
- object o1 = "Some String";
- object o2 = 5;
- string s1 = o1 as string;
- string s2 = o2 as string;
- Console.WriteLine(s1);//"Some String"
- Console.WriteLine(s2);//null
- }
- }
13.sizeof运算符
确定栈中值类型需要的长度(单位:字节)
- class MyClass
- {
- static void Main(string[] args)
- {
- Console.WriteLine(sizeof(int));
- }
- }
14.typeof运算符
返回一个特定类型的System.Type对象。
15.空接合运算符??
- class MyClass
- {
- static void Main(string[] args)
- {
- int? a = null;
- int b;
- b = a ?? 10;
- Console.WriteLine(b);//10
- a = 3;
- b = a ?? 10;
- Console.WriteLine(b);//3
- }
- }
如果第一个操作数不是null,则整个表达式等于第一个操作数的值。如果第一个操作数等于null,则这个表达式等于第二个操作数。
如果第二个操作数不能隐含的转换为第一个操作数的的类型,就生成一个编译错误。
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/12639172/viewspace-464492/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/12639172/viewspace-464492/
本文对比了C#与Java的一些不同之处,详细介绍了C#特有的语法特性,包括@字符串、可空类型、sealed关键字、部分类、只读字段、静态构造函数等。
681

被折叠的 条评论
为什么被折叠?



