標籤:ar io 使用 sp strong on 資料 div art
1.命名空間
C#程式利用命名空間進行組織,命名空間既可以用作程式的內部組織系統,也可以用作向外部公開的組織系統(即一種向其它程式公開自己擁有的程式元素的方法)。
如果要調用某個命名空間中的類或方法,首先需要使用using指令引入命名空間,using指令將命名空間內的類型成員匯入當前編譯單元。using 命名空間名。
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using N1;
- namespace HelloWorld
- {
- class Program
- {
- static void Main(string[] args)
- {
- A mA = new A();
- mA.al();
- }
- }
- }
- namespace N1
- {
- class A
- {
- public void al()
- {
- Console.WriteLine("命名空間樣本");
- Console.ReadLine(); //使程式暫停
- }
- }
- }
2.資料類型
C#資料類型分為兩種,實值型別和參考型別。實值型別直接儲存資料;參考型別儲存對其資料的引用,又稱對象。實值型別可以通過執行裝箱和拆箱操作來按對象處理。
實值型別:整形、浮點型、布爾型、struct
參考型別:string和object,用new建立對象執行個體
c#的類型系統是統一的,object類型是所有類型的父類(預定義類型、使用者定義型別、參考型別、實值型別)。
變數的複製:
int v1 = 0; 整型
int v2 = v1; //值賦值,值並不保持一致
Point p1 = new Point(); 類
Point p2 = p1; //引用賦值,值保持一致
例子:
int intOne = 300; //直接定義
float theFloat = 1.12f;
Console.WriteLine("intOne={0}", intOne); //注意這種輸出方式
Console.ReadLine(); //目的是使程式暫停,以便觀察。按斷行符號鍵退出
結構類型樣本:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace HelloWorld
- {
- struct Point
- {
- public int a;
- public int b;
- public Point(int a, int b) //建構函式
- {
- this.a = a;
- this.b = b;
- }
- public void output()
- {
- Console.WriteLine("面積為:{0}",a*b);
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- Point p = new Point(5,6);
- p.output();
- }
- }
- }
3.變數聲明
與C++的變數聲明相仿,
int a = 99;
string str = "hello";
4.資料類型轉換
(1)隱式類型轉換:
(2)顯式類型轉換:強制類型轉換
double x = 198802.5;
int y = (int)x; //方式一
int y = Convert.ToInt32(x); //使用Convert關鍵字的
string str = Console.ReadLine();
int year = Int32.Parse(str); //從字串中提取整型
C#基礎