string比较时 == 和Equals的区别:
当比较的两者都是string时,== 和 Equals等价。
当其中一者不是string时,比如object, 此时用Equals比较为true时,用==为false.
这一点和Java不同,java必须是引用一致时==才会为true, 而c#不是,可以用ReferenceEquals来验证:
string s1 = "hello";
string s2 = "hello";
System.Console.Out.WriteLine("reference equal: {0}", ReferenceEquals(s1, s2)); //true
StringBuilder sb = new StringBuilder();
sb.Append("xiaoming");
String str = "xiaoming";
System.Console.Out.WriteLine("equal: {0}", str.Equals(sb.ToString())); //true
System.Console.Out.WriteLine("equal: {0}", str == sb.ToString()); //true
System.Console.Out.WriteLine("reference equal: {0}", ReferenceEquals(str, sb.ToString())); //false
object o1 = sb.ToString();
System.Console.Out.WriteLine("equal: {0}", str.Equals(o1)); //true
System.Console.Out.WriteLine("equal: {0}", str == o1); //false
is and typeof:
int nCount = 1;
Console.Out.WriteLine("1 type name:{0}", nCount.GetType().Name); //Int32
Console.Out.WriteLine("1 is int: {0}", nCount is int); //True
Console.Out.WriteLine("1 type is typeof int:{0}", nCount.GetType() == typeof(int)); //True
foreach:
c#:
int[] arr = {1, 2, 3};
foreach(int n in arr)
Console.Out.WriteLine(n);
java:
int arr[] = {1, 2, 3};
for (int n : arr)
System.out.println(n);
inherit:
c++:
可以多重继承。
virtual 修饰虚方法,虚方法的功能就是能够通过父类透传调用子类的方法。
virtual修饰的纯虚方法,格式类似 virtual void GetName() = 0; 包含纯虚方法的类不能被实例化。
c#:
只能单一继承。增加interface的概念,接口可以多重继承。比如基类First,interface Ia, Ib.
interface Ia{...}
class Second : First, Ia, Ib {...}
virtual修饰虚方法,功能同C++类似,但子类重写时需用override 修饰。
没有纯虚的概念,对应的是抽象,方法用abstract修饰实现,同时类也要用abstract修饰。抽象类不能被实例化。 子类用override修饰覆盖的方法。
base关键字来表示父类,方法中可以调用base.method(), 构造函数可以直接跟 : base() 。
java:
类似于c#,只能有一个基类,但可以实现n个接口。如:
class Second extends First implements Ia, Ib {...}
没有virtual的概念,子类只能覆盖父类方法,没办法在转换为父类时调用父类方法。
不想被覆盖的方法可以用final修饰。
子类覆盖方法用@Override修饰。