我需要为这行代码做些什么? (C#)

时间:2009-04-30 15:06:39

标签: c# class

我试图得到一个if语句,说明我的点数组在“i”(在For循环中初始化)是否等于Circle的X和Y(设置为smallcircle.X和smallcircle。 Y)。我知道在if语句中我需要做什么,但我不能让if语句本身起作用。这是什么语法?

目前有:

if (centerPoints[i] == smallcircle.X, smallcircle.Y)

它不喜欢那一点。

6 个答案:

答案 0 :(得分:11)

可能这个:

if (centerPoints[i].X == smallcircle.X && centerPoints[i].Y == smallcircle.Y)

答案 1 :(得分:4)

centerPoints [i]是Point的一个实例,对吗?

在这种情况下,这......

if (centerPoints[i] == new Point(smallcircle.X, smallcircle.Y))

......应该做的伎俩

<强>更新

你的圈子是什么类型的?如果它是你的,那么为什么它没有Point类型的Center属性。这会让你的生活更轻松。

答案 2 :(得分:2)

if ((centerPoints[i].X == smallcircle.X) && (centerPoints[i].Y == smallcircle.Y))

答案 3 :(得分:2)

您正在寻找逻辑AND运算符,它在C#中为&&。它用于检查两个条件是否均为真。

那样:

if( pts[i] == smallcircle.X && pts[i] == smallcircle.Y ) {
 // Both are true so do this...
}

如果要检查EITHER条件是否为真,请使用logial OR运算符,||:

if( pts[i] == smallcircle.X || pts[i] == smallcircle.Y ) {
 // Either one or the other condition is true, so do this...
}

答案 4 :(得分:2)

还有一件事:

如果这是你的for循环正在进行的唯一事情,你可以像这样编写整个循环:

foreach (Point point in centerPoints.Where(p => p.X == smallcircle.X && p.Y == smallcircle.Y) )
{
    //
}

答案 5 :(得分:0)

另一种选择是覆盖Equals()结构中的Point方法,这是我用过的一个例子:

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...
}