教學-44 命名空間和裝箱拆箱
阿新 • • 發佈:2018-02-02
add 不同 ace 封裝 text 類庫 store linq source
曾英-C#教學-44 命名空間和裝箱拆箱
目錄
- 1\認識命名空間,學習如何定義使用命名空間
- 2\學習如何使用幫助
- 3\理解裝箱和拆箱操作
1\命名空間
- 以下都是.Net內部定義的命名空間
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace是自己定義的 namespace _44_命名空間
1.1\namespace
- 如果沒有定義不同的命名空間的話,在出現相同類的時候會出錯.
- 命名空間可以區分各種累進入不同的類(或者同名的類)進入不同的命名空間
程序實例:
調用不同命名空間中的類的方法: using System; using System.Collections.Generic; using System.Linq; using System.Text; //類庫 namespace _44_命名空間 { class Program { static void Main(string[] args) { //引用別的命名空間的類的方法: //在類名前添加一個命名空間的名字 A.Bird f1 = new A.Bird(); f1.Fly(); //輸出結果:A小鳥飛. //引用B命名空間的方法: B.Bird f2 = new B.Bird(); f2.Fly();//輸出結果:B小鳥飛. } } } //類庫 namespace A { class Bird { public void Fly() { Console.WriteLine("A小鳥飛"); } } } namespace B { class Bird { public void Fly() { Console.WriteLine("B小鳥飛"); } } }
1.2\沒有命名空間的時候的處理方法
程序實例:
//using System; //這裏using System被註釋了 /*using System.Collections.Generic; using System.Linq; using System.Text; */ namespace _44_2 { class Program { static void Main(string[] args) { //主函數中每一個方法的前面都需要增加一個System.xxx來實現調用系統方法. double a = 4; double b = System.Math.Sqrt(a); System.Console.WriteLine(b); string cc = System.Console.ReadLine(); int d = System.Convert.ToInt32(b); } } }
1.3\多種命名空間
1.4\嵌套類型命名空間的調用
using System; namespace _44_3_命名空間 { class Program { static void Main(string[] args) { //定義的時候要將兩個命名空間依次寫出 A.AA.bird f1=new A.AA.bird(); f1.Fly(); } } } //這裏套用了兩層命名空間. namespace A { namespace AA { class bird { public void Fly() { Console.WriteLine("a小鳥飛"); } } } namespace AB { } }
2\使用幫助
msdn
3\裝箱和拆箱
-
C#的類型分為值類型和引用類型,
-
值類型:裝箱前n的值存儲在棧中,
-
引用類型:裝箱後n的值被封裝到堆中.
-
這裏,什麽類型都能賦給object型.但是會損失性能.
- 這裏用object類來進行裝箱操作
程序實例:
using System; using System.Collections.Generic; using System.Linq; using System.Text; //這裏如果添加一個 using Ct,主函數中定義的時候就不需要寫 Ct.Storehouse store = new Ct.Storehouse(5);中的Ct. namespace _44_裝拆箱 { class Program { static void Main(string[] args) { Ct.Storehouse store = new Ct.Storehouse(5); //可以使用各種類型 store.Add(100); store.Add(2.14); store.Add("good"); store.Add(new Ct.Storehouse(5)); //遍歷 //這裏是裝箱操作,將多種數據類型都用object類型. foreach (object item in store.Items) { Console.WriteLine(item); } } } } namespace Ct { class Storehouse { //object型數組,可以存儲各種類型數據 public Object[] Items; private int count; //這裏用count為數組計數 public Storehouse(int size) { //數組的初始化 Items = new Object[size]; count = 0; } //數組中添加數據 //為Items添加數據,並判斷數組是否溢出 public void Add(Object obj) { if (count < Items.Length) { Items[count] = obj; count++; } else Console.WriteLine("倉庫已滿"); } } }
教學-44 命名空間和裝箱拆箱