日期:2014-05-18  浏览次数:20871 次

在类内部引用类的实例,参数怎么传递的?
大家看看这个例子:

namespace Classes
{
  class Point
  {
  private int x, y;
  // private static int objectCount=0;
  public Point() 
  {
  this.x = -1;
  this.y = -1;
  }
  public Point(int x, int y)
  {
  this.x = x;
  this.y = y;
   
  }
  public double DistanceTo(Point other)
  {
  int xDiff = this.x - other.x;
  int yDiff = this.y - other.y;
  return Math.Sqrt(xDiff * xDiff + yDiff * yDiff);
  }

  }
}
 class Program
  {
  static void DoWork()
  {
  Point origin=new Point() ;
  Point bottomRight = new Point(1024, 1280);
  double distance = origin.DistanceTo(bottomRight);
  Console.WriteLine("Distance is {0}", distance);
  }

  static void Main(string[] args)
  {
  try
  {
  DoWork();
  }
  catch (Exception ex)
  {
  Console.WriteLine(ex.Message);
  }
  Console.ReadKey();
  }
  }

这里的other.x,other.y应该是other内部的私有字段,为什么,可以在类point里面直接访问?

------解决方案--------------------
私有不是指对类的实例私有而是对类私有
------解决方案--------------------
如果说你的工资是你的私有字段,别人肯定是不知道的(在Program类中你创建的objPoint肯定是看不到x和y的),但是你自己肯定是知道的。
------解决方案--------------------
为什么不可以?

比如我说“人总是会帮助人”,难道不行吗?难道你连基本的语言都会怀疑?如果你想象不到面向对象编程语言不能在定义一个class中去使用这种class的对象参数,那么说明你纯粹是机械地、教条地硬学编程“理论”。
------解决方案--------------------
实例都不可以访问,那还有谁能访问
------解决方案--------------------
sp1234的回答很经典!!!
------解决方案--------------------
你的other是point类创建的实例,即来自于point那肯定可以访问它自己的私有字段啊!看来你对私有还不太明白啊 找本书看看吧
------解决方案--------------------
1 Point是一个类 这个类中有两个私有字段x,y;
2 other是Point类实例化对象,通过other.x,other.y这种方式访问它的私有字段有啥子纠结?