Contrasting C# and Java Syntax(摘录)
http://www.ondotnet.com/pub/a/dotnet/2001/06/14/csharp_4_java.html
1. 简单类型
C#中的primitive type也是object的子类,因此可以直接调用ToString 或 GetType。
如Int是System.Int32的假名,后者继承了System.Object
注意:C#中简单类型仍然是pass-by-value
Java:static final
C#:
const int TWO = 2;
the keyword “readonly”(在声明处或构造函数中可以赋值,可以是动态赋值)
3. switch语句中的差异
C#中不允许fall-through, 否则会有编译错误。
In C#, an explicit break or goto case to a different case is required somewhere in the case to explicitly define the control flow.
如
switch(n)
{
case 1:
cost += 25;
break;
case 2:
cost += 25;
goto case 1;
4.特有的循环语句 foreach
实现了System.Collections.IEnumerable
接口的object都可以使用foreach, 如array.
5.C#中,所有的异常都是run-time exceptions; 都继承了System.Exception.
6. 函数参数修饰符: params, ref, out
(1) params(其实只是为了简化把数组作为函数参数的过程)
方法的最后一个参数如果是数组,可以在这个参数前加params关键词。
public void methodCaller( params int[] a );
and the method can be called with any of
methodCaller( 1 );
methodCaller( 1, 2, 3, 4, 5 );
Inside methodCaller, the parameters can be accessed through the "a" array defined.
定义
private int property;
public int Property {
get {
return this.property;
}
set {
// value is an implicit
variable generated by the
// compiler to represent the parameter
this.property = value;
}
}
使用
int currentValue = Property;
Property = newValue;
8. Extra Accessibility Modifier
internal - this is a new one to Java programmers, as this means that a
member is accessible from the entire assembly. All the objects you define
inside a .cs file (you can define more than one object inside the .cs file,
unlike Java, where you can usually define only one object) have a handle to the
internal member.
class D : B, C {
// B,C可以是class,也可以时interface;如果是一个是class,一个是interface,class要放在interface前面。
* structs are passed by value instead of by reference
* structs cannot extend anything (nor can anything extend them) -- they may, however, implement interfaces
* structs may not define a constructor with no parameters
* structs that define constructors with parameters must explicitly define all fields before they return control to the caller
public virtual void toOverride() { }
public override void toOverride() { }
public class FloorDouble : Object {
private double value;
this.value = Math.Floor( value );
}
get {
return this.value;
}
}
return new FloorDouble( value );
}
return value.Value;
}
}
FloorDouble fl = (FloorDouble)10.5
double d = fl;
(1) 不能引入单独的一个类
(2) alias for long namespace
using short = a.really.long.namespace.theClass;
(3)不与文件系统中的结构对应