详解C#编程中构造函数的使用

2019-12-26 17:30:52于海丽


public class Person
{
  public int age;
  public string name;
}

class TestPerson
{
  static void Main()
  {
    Person person = new Person();

    Console.WriteLine("Name: {0}, Age: {1}", person.name, person.age);
    // Keep the console window open in debug mode.
    Console.WriteLine("Press any key to exit.");
    Console.ReadKey();
  }
}

输出:


 Name: , Age: 0

注意,age 的默认值为 0,name 的默认值为 null。有关默认值的更多信息,请参见 默认值表(C# 参考)。
示例 3
下面的示例说明使用基类初始值设定项。 Circle 类是从通用类 Shape 派生的,Cylinder 类是从 Circle 类派生的。每个派生类的构造函数都使用其基类的初始值设定项。


abstract class Shape
{
  public const double pi = Math.PI;
  protected double x, y;

  public Shape(double x, double y)
  {
    this.x = x;
    this.y = y;
  }

  public abstract double Area();
}

class Circle : Shape
{
  public Circle(double radius)
    : base(radius, 0)
  {
  }
  public override double Area()
  {
    return pi * x * x;
  }
}

class Cylinder : Circle
{
  public Cylinder(double radius, double height)
    : base(radius)
  {
    y = height;
  }

  public override double Area()
  {
    return (2 * base.Area()) + (2 * pi * x * y);
  }
}

class TestShapes
{
  static void Main()
  {
    double radius = 2.5;
    double height = 3.0;

    Circle ring = new Circle(radius);
    Cylinder tube = new Cylinder(radius, height);

    Console.WriteLine("Area of the circle = {0:F2}", ring.Area());
    Console.WriteLine("Area of the cylinder = {0:F2}", tube.Area());

    // Keep the console window open in debug mode.
    Console.WriteLine("Press any key to exit.");
    Console.ReadKey();
  }
}

输出:


  Area of the circle = 19.63
  Area of the cylinder = 86.39


注:相关教程知识阅读请移步到c#教程频道。