c#與java對比
#c#課時01 ##c#與java對比 ###建立: 檔案-新建-專案-VisualC#-控制檯應用程式。 ###結構: C#:
using System;
namespace HelloWorld
{
class Hello
{
static void Main()
{
Console.WriteLine("Hello World!");
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
}
JAVA:
import java.io.*; package cn.easycomm.test; public class HelloWorld{ public static void main(String[] args) { System.out.println("Hello World!"); } }
namespace
與package
using
與import
注:using有另一種用法
Main
與main
###資料型別:
-
C# 提供 Java 中可用的所有資料型別,並增加了對無符號數字和新的 128 位高精度浮點型別的支援。
-
Java 的
boolean
在 C# 中稱為bool
-
常量,Java 使用
final
欄位修飾符宣告此類變數,而 C# 則使用const
關鍵字const int NUM = 1; //c# public static final int NUM = 1; //java
-
字串,Java用
equals
,C#可以直接用==
或!=
-
轉義字元,都使用
\
,C#中字串開始前使用@
宣告字串則不需轉義字元
###運算子
- C# 提供 Java 支援的所有適用的運算子
- C# 中可用但 Java 中沒有的一些新運算子(
checked
,unchecked
...)
###流控制
-
在 Java 和 C# 這兩種語言中,
if
else
完全相同 -
switch,C# 要求在每個
case
的末尾都使用break
,case
-
在 C# 和 Java 中,
for
迴圈的語法和操作相同 -
C#中引入了
foreach
,Java中使用的是for
C#
static void Main() { string[] arr= new string[] {"Jan", "Feb", "Mar"}; foreach (string s in arr) { System.Console.WriteLine(s); } }
Java
for (String x : list) { System.out.println(x); }
-
while
和do...while
語句的語法和操作是相同的
###引數傳遞
-
在 Java 和 C# 中,引用物件的方法引數始終都是通過引用傳遞的,而基元資料型別引數(C# 中的值型別)是通過值傳遞的。
-
在 C# 中,若要通過引用傳遞值型別,需要指定關鍵字
ref
或out
ref
class TestRef { private static void Add(int i, ref int result) { result += i; return; } static void Main() { int total = 20; System.Console.WriteLine("Original value of 'total': {0}", total); Add(10, ref total); System.Console.WriteLine("Value after calling Add(): {0}", total); } } Original value of 'total': 20 Value after calling Add(): 30
out
class TestOut { private static void Add(int i, int j, out int result) { // The following line would cause a compile error: // System.Console.WriteLine("Initial value inside method: {0}", result); result = i + j; return; } static void Main() { int total = 20; System.Console.WriteLine("Original value of 'total': {0}", total); Add(33, 77, out total); System.Console.WriteLine("Value after calling Add(): {0}", total); } } Original value of 'total': 20 Value after calling Add(): 110
###屬性
-
get
,set
方法public class Animal { public string Age { get; set; } private string name; public string Species { get { return name; } set { name = value; } } }
-
訪問屬性
animal.Species = "Lion"; // set accessor System.Console.WriteLine(animal.Species); // get accessor
###陣列
-
定義初始化
int[] arr2Lines; //int arr2[]; //compile error arr2Lines = new int[5] {1, 2, 3, 4, 5}; int[] arr1Line = {1, 2, 3, 4, 5};
###繼承與介面
- 在 C# 中,繼承及介面實現均由 : 運算子定義,此運算子與 Java 中的 extends 和 implements 等效
- base與super,訪問基類
###異常
-
C# 中的異常處理與 Java 中的異常處理非常相似
-
Exception 為所有異常類的基類
try { // code to open and read a file } catch (System.IO.FileNotFoundException e) { // handle the file not found exception first } catch (System.IO.IOException e) { // handle any other IO exceptions second } catch { // a catch block without a parameter // handle all other exceptions last } finally { // this is executed whether or not an exception occurs // use to release any external resources }
###C#高階技術
-
屬性(類似Java中的批註)
[System.Serializable()] //可以被序列化 public class Employee { public int ID; public string Name; [System.NonSerialized()] public int Salary; }
-
事件與委託(把方法當成型別,傳遞方法)
-
LINQ查詢表示式
-
Lambda表示式
##2、c#常用操作
###常用集合
-
ArrayList
http://msdn.microsoft.com/zh-cn/library/vstudio/system.collections.arraylist_methods(v=vs.90).aspx
-
Hashtable
http://msdn.microsoft.com/zh-cn/library/vstudio/system.collections.hashtable(v=vs.100).aspx
-
Dictionary
http://msdn.microsoft.com/zh-cn/library/vstudio/ms132468(v=vs.90).aspx ###檔案操作
-
檔案讀寫
class TestFileIO { static void Main() { string fileName = "test.txt"; // a sample file name // Delete the file if it exists. if (System.IO.File.Exists(fileName)) { System.IO.File.Delete(fileName); } // Create the file. using (System.IO.FileStream fs = System.IO.File.Create(fileName, 1024)) { // Add some information to the file. byte[] info = new System.Text.UTF8Encoding(true).GetBytes("This is some text in the file."); fs.Write(info, 0, info.Length); } // Open the file and read it back. using (System.IO.StreamReader sr = System.IO.File.OpenText(fileName)) { string s = ""; while ((s = sr.ReadLine()) != null) { System.Console.WriteLine(s); } } } }
###資料庫
-
連線資料庫
using System; using System.Data; using System.Data.SqlClient; class Program { static void Main() { string connectionString = "Data Source=(local);Initial Catalog=Northwind;" + "Integrated Security=SSPI"; string queryString = "SELECT CategoryID, CategoryName FROM dbo.Categories;"; using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = connection.CreateCommand(); command.CommandText = queryString; try { connection.Open(); SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { Console.WriteLine("\t{0}\t{1}", reader[0], reader[1]); } reader.Close(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } }
###Links
-
C#(針對Java開放人員)
http://msdn.microsoft.com/zh-cn/library/ms228358(v=vs.90).aspx
-
C#程式設計指南
from: https://github.com/xfans/Csharp_java_book/blob/master/csharp01.md