• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

C#类和属性的使用

OC/C/C++ 水墨上仙 1739次浏览

C#类和属性的使用

abstractshape.cs

// abstractshape.cs
// 编译时使用:/target:library
// csc /target:library abstractshape.cs
using System;
public abstract class Shape
{
   private string myId;
   public Shape(string s)
   {
      Id = s;   // 调用 Id 属性的 set 访问器
   }
   public string Id
   {
      get 
      {
         return myId;
      }
      set
      {
         myId = value;
      }
   }
   // Area 为只读属性 - 只需要 get 访问器:
   public abstract double Area
   {
      get;
   }
   public override string ToString()
   {
      return Id + " Area = " + string.Format("{0:F2}",Area);
   }
}

shapes.cs

// shapes.cs
// 编译时使用:/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
      {
         // 已知边长,返回正方形的面积:
         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
      {
         // 已知半径,返回圆的面积:
         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
      {
         // 已知宽度和高度,返回矩形的面积:
         return myWidth * myHeight;
      }
   }
}

shapetest.cs

// shapetest.cs
// 编译时使用:/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);
      }
         
   }
}


开心洋葱 , 版权所有丨如未注明 , 均为原创丨未经授权请勿修改 , 转载请注明C#类和属性的使用
喜欢 (0)
加载中……