C#之属性及其示范代码

来源:互联网 发布:网络赌托 编辑:程序博客网 时间:2024/05/21 15:43

 C++在对于类中的某自属性的读取和保存是自定义Get和Set函数来完成的。那么C#提供了更人性化,客户程序调用更简便的实现方式,编译程序会自动生成Getter和Setter函数接口,非常便利。如下是示范代码:

 

 class MyPoint
 {
  protected int _x; //或者Private,防止外部直接访问
  protected int _y; //或者Private,防止外部直接访问

  public int x          
  {
   get
   {
    return _x;
   }
   set
   {
    _x=value;
   }
  }

  public int y
  {
   get
   {
    return _y;
   }
   set
   {
    _y=value;
   }
  }
 }

  static void Main(string[] args)
  {
   //
   // TODO: 在此处添加代码以启动应用程序
   //
   MyPoint p = new MyPoint();
   p.x = 10;
   p.y = 33;

   Console.WriteLine("the point is: {0}:{1}",p.x,p.y);
   Console.ReadLine();
  }
C#编译器在编译时自动生成了Get__x、Get__y方法和Set__x、Set__y方法。

原创粉丝点击