C#基礎

來源:互聯網
上載者:User

標籤:ar   io   使用   sp   strong   on   資料   div   art   

1.命名空間

C#程式利用命名空間進行組織,命名空間既可以用作程式的內部組織系統,也可以用作向外部公開的組織系統(即一種向其它程式公開自己擁有的程式元素的方法)。

如果要調用某個命名空間中的類或方法,首先需要使用using指令引入命名空間,using指令將命名空間內的類型成員匯入當前編譯單元。using 命名空間名。

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using N1;  
  6. namespace HelloWorld  
  7. {  
  8.     class Program  
  9.     {  
  10.         static void Main(string[] args)  
  11.         {  
  12.             A mA = new A();  
  13.             mA.al();  
  14.         }  
  15.     }  
  16. }  
  17. namespace N1  
  18. {  
  19.     class A  
  20.     {  
  21.         public void al()  
  22.         {  
  23.             Console.WriteLine("命名空間樣本");  
  24.             Console.ReadLine();  //使程式暫停  
  25.         }  
  26.     }  
  27. }  

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(); //目的是使程式暫停,以便觀察。按斷行符號鍵退出

結構類型樣本: 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. namespace HelloWorld  
  6. {  
  7.     struct Point   
  8.     {  
  9.         public int a;  
  10.         public int b;  
  11.         public Point(int a, int b)  //建構函式  
  12.         {  
  13.             this.a = a;  
  14.             this.b = b;  
  15.         }  
  16.         public void output()  
  17.         {  
  18.             Console.WriteLine("面積為:{0}",a*b);  
  19.         }  
  20.     }  
  21.     class Program  
  22.     {  
  23.         static void Main(string[] args)  
  24.         {  
  25.             Point p = new Point(5,6);  
  26.             p.output();  
  27.         }  
  28.     }  
  29. }   

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#基礎

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.