AutoCAD 3DMAX C语言 Pro/E UG JAVA编程 PHP编程 Maya动画 Matlab应用 Android
Photoshop Word Excel flash VB编程 VC编程 Coreldraw SolidWorks A Designer Unity3D
 首页 > .NET技术

C# 程序员参考--属性教程

51自学网 http://www.51zixue.net

 

文件 1:abstractshape.cs

该文件声明包含 double 类型的 Area 属性的 Shape

// abstractshape.cs// compile with: /target:library// csc /target:library abstractshape.csusing 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.dllpublic 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.dllpublic 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 CollectionSquare #1 Area = 25.00Circle #1 Area = 28.27Rectangle #1 Area = 20.00

 
 

上一篇:C# 程序员参考--库教程  下一篇:C# 程序员参考--数组教程三