[英]What do I need to do for this line of code? (C#)
我正在尝试获得一个if语句,该语句说明我在“ i”处的点数组(在For循环中初始化)是否等于圆的X和Y(将其设置为smallcircle.X和smallcircle.Y)。 我知道我需要在if陈述中做些什么,但是我无法使if陈述本身起作用。 它的语法是什么?
目前拥有:
if (centerPoints[i] == smallcircle.X, smallcircle.Y)
一点都不喜欢。
大概是这样的:
if (centerPoints[i].X == smallcircle.X && centerPoints[i].Y == smallcircle.Y)
centerPoints [i]是Point的实例,对不对?
在这种情况下...
if (centerPoints[i] == new Point(smallcircle.X, smallcircle.Y))
...应该可以
更新
您的圈子是什么类型? 如果是您的,那为什么不具有Point类型的Center属性。 这会使您的生活更轻松。
if ((centerPoints[i].X == smallcircle.X) && (centerPoints[i].Y == smallcircle.Y))
您正在寻找逻辑AND运算符,在C#中为&&
。 用于检查两个条件是否都成立。
以便:
if( pts[i] == smallcircle.X && pts[i] == smallcircle.Y ) {
// Both are true so do this...
}
如果要检查EITHER条件是否为真,请使用逻辑OR运算符||:
if( pts[i] == smallcircle.X || pts[i] == smallcircle.Y ) {
// Either one or the other condition is true, so do this...
}
还有一件事:
如果这是您的for循环唯一要做的事情,则可以这样编写整个循环:
foreach (Point point in centerPoints.Where(p => p.X == smallcircle.X && p.Y == smallcircle.Y) )
{
//
}
另一种选择是在Point
结构中重写Equals()
方法,这是我使用的一个示例:
struct Point
{
public int X;
public int Y;
public Point(int x, int y) { X = x; Y = y; }
public override bool Equals(object obj)
{
return obj is Point && Equals((Point)obj);
}
public bool Equals(Point other)
{
return (this.X == other.X && this.Y == other.Y);
}
public override int GetHashCode()
{
return X ^ Y;
}
public override string ToString()
{
return String.Format("({0}, {1})", X, Y);
}
public static bool operator ==(Point lhs, Point rhs)
{
return (lhs.Equals(rhs));
}
public static bool operator !=(Point lhs, Point rhs)
{
return !(lhs.Equals(rhs));
}
public static double Distance(Point p1, Point p2)
{
return Math.Sqrt((p1.X - p2.X) * (p1.X - p2.X) + (p1.Y - p2.Y) * (p1.Y - p2.Y));
}
}
因此,您的代码将变为:
Point smallcircle = new Point(5, 5);
if (centerPoints[i] == smallcircle)
{
// Points are the same...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.