为什么可以';我用C#中的两个参数调用这个构造函数吗?
我是C#的新手,我正在学习范围。只需编写一个简单的程序,根据直线上两个端点的坐标计算直线的长度。在下面代码的第7行中,我得到一个编译器错误,表示line类的构造函数不能接受两个参数。为什么呢?然后在第30行和第31行附近,我无法得到GetLength方法来识别右下角点和原点。任何建议都将不胜感激,谢谢为什么可以';我用C#中的两个参数调用这个构造函数吗?,c#,C#,我是C#的新手,我正在学习范围。只需编写一个简单的程序,根据直线上两个端点的坐标计算直线的长度。在下面代码的第7行中,我得到一个编译器错误,表示line类的构造函数不能接受两个参数。为什么呢?然后在第30行和第31行附近,我无法得到GetLength方法来识别右下角点和原点。任何建议都将不胜感激,谢谢 class Program { static void doWork() { Point origin = new Point(0,0); Poin
class Program
{
static void doWork()
{
Point origin = new Point(0,0);
Point bottomRight = new Point(1366, 768);
Line myLine = new Line(bottomRight, origin);
//double distance = origin.DistanceTo(bottomRight);
double distance = GetLength(myLine);
Console.WriteLine("Distance is: {0}", distance);
Console.WriteLine("Number of Point objects: {0}", Point.ObjectCount());
Console.ReadLine();
}
static void Main(string[] args)
{
try
{
doWork();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
static double GetLength(Line line)
{
Point pointA = line.bottomRight;
Point pointB = line.origin;
return pointA.DistanceTo(pointB);
}
}
class Line
{
static void Line(Point pointA, Point pointB)
{
pointA = new Point();
pointB = new Point();
}
}
下面是Point类的代码:
class Point
{
private int x, y;
private static int objectCount = 0;
public Point()
{
this.x = -1;
this.y = -1;
objectCount++;
}
public Point(int x, int y)
{
this.x = x;
this.y = y;
objectCount++;
}
public double DistanceTo(Point other)
{
int xDiff = this.x - other.x;
int yDiff = this.y - other.y;
double distance = Math.Sqrt((xDiff * xDiff) + (yDiff * yDiff));
return distance;
}
public static int ObjectCount()
{
return objectCount;
}
}
不要使用void
public Line(Point pointA, Point pointB)
{
pointA = new Point();
pointB = new Point();
}
您的
行
类看起来不完整。它不存储任何数据。它应该更像这样:
class Line
{
public Point BottomRight { get; set; }
public Point Origin { get; set; }
public Line(Point pointA, Point pointB)
{
Origin = pointA;
BottomRight = pointB;
}
}
然后只需在GetLength
方法中更改line.BottomRight
和line.Origin
:
static double GetLength(Line line)
{
Point pointA = line.BottomRight;
Point pointB = line.Origin;
return pointA.DistanceTo(pointB);
}
现在应该可以了看看你对Line类的定义。没有支持变量….
静态虚线(点a、点B)
不是构造函数。将static void
更改为public
。您尚未为行定义任何构造函数。所以它只有一个没有参数的默认值。因此,没有具有两个参数的构造函数。它也没有名为bottomRight
或origin
的成员,因此您无法访问不存在的成员。我通过使用“public”删除“static void”修复了构造函数,但现在GetLength方法出现了问题。我无法用这种方法识别线条myLine对象中的两个变量,bottomRight和origin。我怎样才能访问这些呢?@shampouya我不是故意粗鲁,但我要说的是,你在编程时会遇到很多问题,在C#development中学习速成课程可能比在C#development上实时调试/学习应用程序更有益。实际上,我目前正在学习C#development速成课程7天。这是我们的第一次课堂练习,我正在努力完成。在我的程序中,有人知道我如何访问MyLin对象中的点变量吗?@“Shanpouya,欢迎你:”但是你应该考虑接受答案而不是评论。查看您的个人资料,我不确定您是否意识到这种做法:)