gpt4 book ai didi

c# - 在 C# 中,有效的返回值在接收器中变为 null

转载 作者:行者123 更新时间:2023-11-30 18:02:42 25 4
gpt4 key购买 nike

我刚接触 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 结构使用 double 值的问题。我知道在我的应用程序中,位置值始终是整数,所以我没有使用 .NET 点并创建了我自己的点:

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

提前致谢!

最佳答案

我尽可能简洁地实现了你的代码,在适当的地方做了一些模拟(下面的代码),我不能让它失败。我的代码示例中缺少什么:

class Program
{
static void Main(string[] args)
{
LoadMarkers();
var location = new Point(45, 45);
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));

}
public static List<Marker> Markers = new List<Marker>();
private static void LoadMarkers()
{
for (var q = 0; q < 50; q++)
for (var w = 0; w < 50; w++)
Markers.Add(new Marker(q, w));
}
public static Marker markerAtLocation(Point location)
{
foreach (Marker nextMarker in Markers)
if (nextMarker.Location().Equals(location))
return nextMarker;
return null;
}
}
class Marker
{
private Point _loc;
public Marker(int x, int y) { _loc = new Point(x, y); }
public Point Location() { return _loc; }
}
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));
}
}

关于c# - 在 C# 中,有效的返回值在接收器中变为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7983767/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com