隨風設計

          隨風設計

            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理 ::
            11 隨筆 :: 0 文章 :: 0 評論 :: 0 Trackbacks

          本教程展示屬性是如何成為 C# 編程語言必不可少的一個組成部分的。它闡釋如何聲明和使用屬性。
          教程

          此教程包括兩個示例。第一個示例展示如何聲明和使用讀/寫屬性。第二個示例演示抽象屬性并展示如何在子類中重寫這些屬性。

          示例 1

          本示例展示一個 Person 類,它有兩個屬性:Name (string) 和 Age (int)。兩個屬性都是讀/寫屬性。

          // person.cs
          using System;
          class Person
          {
              private string myName ="N/A";
              private int myAge = 0;
          
              // Declare a Name property of type string:
              public string Name
              {
                  get 
                  {
                     return myName; 
                  }
                  set 
                  {
                     myName = value; 
                  }
              }
          
              // Declare an Age property of type int:
              public int Age
              {
                  get 
                  { 
                     return myAge; 
                  }
                  set 
                  { 
                     myAge = value; 
                  }
              }
          
              public override string ToString()
              {
                  return "Name = " + Name + ", Age = " + Age;
              }
          
              public static void Main()
              {
                  Console.WriteLine("Simple Properties");
          
                  // Create a new Person object:
                  Person person = new Person();
          
                  // Print out the name and the age associated with the person:
                  Console.WriteLine("Person details - {0}", person);
          
                  // Set some values on the person object:
                  person.Name = "Joe";
                  person.Age = 99;
                  Console.WriteLine("Person details - {0}", person);
          
                  // Increment the Age property:
                  person.Age += 1;
                  Console.WriteLine("Person details - {0}", person);
              }
          }

          輸出

          Simple Properties
          Person details - Name = N/A, Age = 0
          Person details - Name = Joe, Age = 99
          Person details - Name = Joe, Age = 100

          代碼討論

          • 請注意聲明屬性的方式,例如,考慮 Name 屬性:
            public string Name
            {
                get 
                {
                   return myName; 
                }
                set 
                { 
                   myName = value; 
                }
            }

            屬性的“設置”(Set) 方法和“獲取”(Get) 方法包含在屬性聲明中。可以通過控制是否包含“獲取”方法或“設置”方法來控制屬性是讀/寫屬性、只讀屬性還是只寫屬性。

          • 聲明了屬性后,可像使用類的字段那樣使用這些屬性。這使得獲取和設置屬性值時都可以使用非常自然的語法,如以下語句中所示:
            person.Name = "Joe";
            person.Age = 99;
          • 注意屬性“設置”方法中可以使用一個特殊的 value 變量。該變量包含用戶指定的值,例如:
            myName = value; 
          • 請注意用于使 Person 對象上的 Age 屬性遞增的簡潔語法:
            person.Age += 1;

            如果使用單獨的“設置”方法和“獲取”方法建立屬性模型,等效代碼可能是:

            person.SetAge(person.GetAge() + 1);
          • 本示例中重寫了 ToString 方法:
            public override string ToString()
            {
                return "Name = " + Name + ", Age = " + Age;
            }

            注意程序中未顯式使用 ToString。默認情況下,它由 WriteLine 調用來調用。

          示例 2

          下面的示例展示如何定義抽象屬性。抽象屬性聲明不提供屬性訪問器的實現。本示例演示如何在子類中重寫這些屬性。

          該示例包含三個文件。在“屬性”示例中,這些文件被編譯為單個編譯;但在此教程中,每個文件都單獨進行編譯,且產生的程序集會由下一個編譯引用:

          • abstractshape.cs:包含抽象 Area 屬性的 Shape 類。
          • shapes.cs:Shape 類的子類。
          • shapetest.cs:一個測試程序,它顯示某些 Shape 派生的對象的面積。

          若要編譯該示例,請使用命令行:

          csc abstractshape.cs shapes.cs shapetest.cs

          這樣將生成可執行文件 shapetest.exe。

          文件 1:abstractshape.cs

          該文件聲明包含 double 類型的 Area 屬性的 Shape

          // abstractshape.cs
          // compile with: /target:library
          // csc /target:library abstractshape.cs
          using System;
          
          public abstract class Shape
          {
             private string myId;
          
             public Shape(string s)
             {
                Id = s;   // calling the set accessor of the Id property
             }
          
             public string Id
             {
                get 
                {
                   return myId;
                }
          
                set
                {
                   myId = value;
                }
             }
          
             // Area is a read-only property - only a get accessor is needed:
             public abstract double Area
             {
                get;
             }
          
             public override string ToString()
             {
                return Id + " Area = " + string.Format("{0:F2}",Area);
             }
          }

          代碼討論

          • 屬性的修飾符就放在屬性聲明語句中,例如:
            public abstract double Area
          • 聲明抽象屬性時(如本示例中的 Area),指明哪些屬性訪問器可用即可,不要實現它們。本示例中,只有“獲取”(Get) 訪問器可用,因此屬性為只讀屬性。

          文件 2:shapes.cs

          下面的代碼展示 Shape 的三個子類,并展示它們如何重寫 Area 屬性來提供自己的實現。

          // shapes.cs
          // compile with: /target:library /reference:abstractshape.dll
          public class Square : Shape
          {
             private int mySide;
          
             public Square(int side, string id) : base(id)
             {
                mySide = side;
             }
          
             public override double Area
             {
                get
                {
                   // Given the side, return the area of a square:
                   return mySide * mySide;
                }
             }
          }
          
          public class Circle : Shape
          {
             private int myRadius;
          
             public Circle(int radius, string id) : base(id)
             {
                myRadius = radius;
             }
          
             public override double Area
             {
                get
                {
                   // Given the radius, return the area of a circle:
                   return myRadius * myRadius * System.Math.PI;
                }
             }
          }
          
          public class Rectangle : Shape
          {
             private int myWidth;
             private int myHeight;
          
             public Rectangle(int width, int height, string id) : base(id)
             {
                myWidth  = width;
                myHeight = height;
             }
          
             public override double Area
             {
                get
                {
                   // Given the width and height, return the area of a rectangle:
                   return myWidth * myHeight;
                }
             }
          }

          文件 3:shapetest.cs

          以下代碼展示一個測試程序,它創建若干 Shape 派生的對象,并輸出它們的面積。

          // shapetest.cs
          // compile with: /reference:abstractshape.dll;shapes.dll
          public class TestClass
          {
             public static void Main()
             {
                Shape[] shapes =
                   {
                      new Square(5, "Square #1"),
                      new Circle(3, "Circle #1"),
                      new Rectangle( 4, 5, "Rectangle #1")
                   };
                
                System.Console.WriteLine("Shapes Collection");
                foreach(Shape s in shapes)
                {
                   System.Console.WriteLine(s);
                }
                   
             }
          }

          輸出

          Shapes Collection
          Square #1 Area = 25.00
          Circle #1 Area = 28.27
          Rectangle #1 Area = 20.00
          posted on 2006-08-17 11:32 曹賢 閱讀(216) 評論(0)  編輯  收藏

          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 牟定县| 孙吴县| 六安市| 桐乡市| 延川县| 南澳县| 淳化县| 法库县| 广安市| 建德市| 云梦县| 海口市| 达拉特旗| 巨野县| 宝鸡市| 三河市| 曲松县| 赤城县| 兴隆县| 德令哈市| 泰安市| 崇礼县| 平谷区| 南华县| 宿州市| 武安市| 犍为县| 上犹县| 射阳县| 石泉县| 清水河县| 嘉定区| 封开县| 舒兰市| 浦北县| 陇南市| 鄂尔多斯市| 阿克| 长沙县| 四川省| 泽普县|