返回列表 發帖

[9-3]namespace and using

本帖最後由 李泳霖 於 2024-1-9 11:20 編輯

namespace 為一個空間,可以存放很多模板的空間,功用:分類與管理模板,如同資料夾般
如下:
Person這個模板(類別clss)是屬於Animal這個空間的
  1. namespace Animal
  2. {
  3.     class Person
  4.     {
  5.         public double height;
  6.         public int age;
  7.         public string name;

  8.     }
  9. }
  10. namespace house
  11. {

  12. }
複製代碼
所以當有人要使用到Person,必須使用以下方法
  1. Animal.Person person1 = new Animal.Person();//顯得麻煩
  2. person1.height = 150;
  3. person1.age = 42;
  4. person1.name = "大大";

  5. Animal.Person person2 = new Animal.Person();
  6. person2.height = 180;
  7. person2.age = 20;
  8. person2.name = "小小";


  9. System.Console.WriteLine("姓名: "+person1.name);
  10. System.Console.WriteLine("年齡: " + person1.age);
  11. System.Console.WriteLine("身高: " + person1.height);

  12. System.Console.WriteLine("==================================");
  13. System.Console.WriteLine("姓名: " + person2.name);
  14. System.Console.WriteLine("年齡: " + person2.age);
  15. System.Console.WriteLine("身高: " + person2.height);
複製代碼
  1. //class 、 object
  2. using Animal;
  3. using System;
  4. Person person1 = new Person();
  5. person1.height = 150;
  6. person1.age = 42;
  7. person1.name = "大大";

  8. Person person2 = new Person();
  9. person2.height = 180;
  10. person2.age = 20;
  11. person2.name = "小小";


  12. Console.WriteLine("姓名: "+person1.name);
  13. Console.WriteLine("年齡: " + person1.age);
  14. Console.WriteLine("身高: " + person1.height);

  15. Console.WriteLine("==================================");
  16. Console.WriteLine("姓名: " + person2.name);
  17. Console.WriteLine("年齡: " + person2.age);
  18. Console.WriteLine("身高: " + person2.height);
複製代碼
namespace 內也可以再新增namespace
如下所示:
  1. namespace Animal
  2. {
  3.     namespace qq
  4.     {
  5.         class Person
  6.         {
  7.             public double height;
  8.             public int age;
  9.             public string name;

  10.         }
  11.     }

  12. }
  13. namespace house
  14. {

  15. }
複製代碼
  1. //class 、 object
  2. using Animal.qq;
  3. using System;
  4. Person person1 = new Person();
  5. person1.height = 150;
  6. person1.age = 42;
  7. person1.name = "大大";

  8. Person person2 = new Person();
  9. person2.height = 180;
  10. person2.age = 20;
  11. person2.name = "小小";


  12. Console.WriteLine("姓名: "+person1.name);
  13. Console.WriteLine("年齡: " + person1.age);
  14. Console.WriteLine("身高: " + person1.height);

  15. Console.WriteLine("==================================");
  16. Console.WriteLine("姓名: " + person2.name);
  17. Console.WriteLine("年齡: " + person2.age);
  18. Console.WriteLine("身高: " + person2.height);
複製代碼
istak.teach2@gmail.com

返回列表