大家看看这个例子: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里面直接访问?

解决方案 »

  1.   

    如果说你的工资是你的私有字段,别人肯定是不知道的(在Program类中你创建的objPoint肯定是看不到x和y的),但是你自己肯定是知道的。
      

  2.   

    我的疑问是 other是point的一个实例,那么other.x,other.y就应该是other内部的私有字段(因为在类point内部定义了private int x, y)
    为什么在point类内部,可以直接访问other内部的私有字段呢?
      

  3.   

    为什么不可以?比如我说“人总是会帮助人”,难道不行吗?难道你连基本的语言都会怀疑?如果你想象不到面向对象编程语言不能在定义一个class中去使用这种class的对象参数,那么说明你纯粹是机械地、教条地硬学编程“理论”。
      

  4.   

    谢谢大家的帮助和批评,总算有点头绪了。
    我感觉自己经常会钻牛角尖,有点笨。
    我可不可以这么理解:point 可以访问 它的任意一个实例的私有字段,但是,反过来,它的实例与实例之间则不可以访问私有字段,是不是这样?
      

  5.   

    你的other是point类创建的实例,即来自于point那肯定可以访问它自己的私有字段啊!看来你对私有还不太明白啊 找本书看看吧
      

  6.   

    谢谢大家的帮助和批评,总算有点头绪了。
    我感觉自己经常会钻牛角尖,有点笨。
    我可不可以这么理解:point 可以访问 它的任意一个实例的私有字段,但是,反过来,它的实例与实例之间则不可以访问私有字段,是不是这样? 
      

  7.   

    1   Point是一个类  这个类中有两个私有字段x,y;
    2   other是Point类实例化对象,通过other.x,other.y这种方式访问它的私有字段有啥子纠结?