我只是进入C#,所以如果这是一个基本问题,请原谅我。我正在使用.NET 4.0和VS 2010构建WPF应用程序。
我有一个用于存储对象List
的类;这些对象具有一个Point对象作为字段。方法之一返回列表中特定位置的对象:
public Marker markerAtLocation(Point location) {
foreach (Marker nextMarker in Markers)
if (nextMarker.Location().Equals(location))
return nextMarker;
return null;
}
设置断点并使用
Console.WriteLine
我已经确认nextMarker
在返回时是有效的。但是,在接收方中,对象始终为null
:Marker top = markerAtLocation(new Point(location.X, location.Y + 1));
if (top == null)
Console.WriteLine("Top is null");
else
Console.WriteLine("Top is " + top.ToString());
Marker bottom = markerAtLocation(new Point(location.X, location.Y - 1));
if ((bottom != null) && (bottom.player == otherPlayerType()) && (top != null) && (top.player == otherPlayerType()))
return true;
我不知道这里出了什么问题…
请注意,我最初认为这是使用双精度值的.NET的
Point
结构的问题。我知道在我的应用中,位置值将始终为整数,因此我没有使用.NET Point而是创建了自己的位置:class Point {
public int X, Y;
public Point(int X, int Y) {
this.X = X;
this.Y = Y;
}
public bool Equals(Point anotherPoint) {
return ((anotherPoint.X == X) && (anotherPoint.Y == Y));
}
}
我将不胜感激!
编辑:回应pbirkoff:
class Grid {
public List<Marker> Markers;
public Grid() {
Markers = new List<Marker>();
}
public Grid(List<Marker> markers) {
this.Markers = markers;
}
public void addMarker(Marker newMarker) {
Markers.Add(newMarker);
}
我已尽力尝试了以下解决方案,但没有一个有帮助。我包括到项目本身以及我要解决的问题的链接。
项目:http://dl.dropbox.com/u/7828009/ACSLPetteia.zip
问题:http://wcipeg.com/etc/ACSL/VOL%2030/ACSL%20Petteia_sr_3.doc
提前致谢!
最佳答案
首先,我将更改您的班级名称。命名空间通常会处理所有冲突,但是在System.Windows中定义的WPF点在尝试在WPF Window类中创建Point时很可能会引起问题,我猜这是接收者代码所在的位置位于。我说这的原因是,默认情况下您会获得“使用System.Windows;”。 VS创建的自动生成的Window类顶部的行。
由于一切都是从对象派生的,因此您也将要覆盖bool Equals(object o)函数,因为这将帮助您解决与System.Windows.Point而不是Point进行比较的问题。
我认为,如果将类的名称更改为IntPoint,则可能会发现接收代码中的“新Point”可能无法重构为“新IntPoint”,因为它可以解析为System.Windows.Point。
使用Grid作为名称也是如此。我尝试遵守不使用与.NET类型名称匹配的类型名称的约定,以避免出现奇数冲突。
综上所述,将您的课程更改为以下内容:
class IntPoint {
public int X { get; set; }
public int Y { get; set; }
public IntPoint(int X, int Y) {
this.X = X;
this.Y = Y;
}
public override bool Equals(object obj)
{
if (obj is IntPoint) return Equals(obj as IntPoint);
return base.Equals(obj);
}
public bool Equals(IntPoint anotherPoint) {
return ((anotherPoint.X == X) && (anotherPoint.Y == Y));
}
}
我还使用速记默认get / set语法将您的公共字段更改为公共属性。我不会介绍属性与字段的详细信息,但是对您在网上搜索.net属性与公共字段比较有好处。推理的一部分与绑定的工作方式有关。 .Net允许您绑定到属性,但是如果您尝试绑定到其中一个字段,我相信它将无法找到它们。
如果您进行了这些更改,但仍无法正常工作,请回发。
关于c# - 有效返回值在C#中的接收器中变为空,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7983767/