随风设计

随风设计

  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 曹贤 阅读(199) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: