大家看看这个例子: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里面直接访问?
{
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里面直接访问?
为什么在point类内部,可以直接访问other内部的私有字段呢?
我感觉自己经常会钻牛角尖,有点笨。
我可不可以这么理解:point 可以访问 它的任意一个实例的私有字段,但是,反过来,它的实例与实例之间则不可以访问私有字段,是不是这样?
我感觉自己经常会钻牛角尖,有点笨。
我可不可以这么理解:point 可以访问 它的任意一个实例的私有字段,但是,反过来,它的实例与实例之间则不可以访问私有字段,是不是这样?
2 other是Point类实例化对象,通过other.x,other.y这种方式访问它的私有字段有啥子纠结?