我被一段从 Java 转换为 C# 的代码所困扰。
基本上,我有一个 Map(字典),其键由 Pair 组成,值由我创建的类(Square)表示;在这个类中只有一个字段,它是可选的(是的,我在 C# 中创建了可选类)。
一开始,我用对来填充这个字典,以形成一个相似网格和空可选,如下面的代码所示。
class World
{
private Dictionary<Pair<int, int>, Square> map =
new Dictionary<Pair<int, int>, Square>();
public World(int width, int height)
{
this.size = new Pair<int, int>(width, height);
for (int w = 0; w < this.size.GetX(); w++)
{
for (int h = 0; h < this.size.GetY(); h++)
this.map.Add(new Pair<int, int>(w, h),
new Square(Optional<Entity>.Empty()));
}
}
}
这是 Square 类
class Square
{
private Optional<Entity> entity;
public Square (Optional<Entity> entity)
{
this.entity = entity;
}
public Optional<Entity> GetEntity()
{
return this.entity;
}
public void SetEntity(Optional<Entity> entity)
{
this.entity = entity;
}
}
问题来了,当我尝试从字典中获取现有值时,下面的这个函数总是返回null,它抛出System.NullReferenceException:对象引用未设置为对象的实例。 在这段代码中,我删除了所有控件,但我知道我尝试获取已插入的值;另外,我尝试运行 Dictionary.ContainsValue 但它返回 false!但我确实已经初始化了字典。
public Square? GetSquare(int x, int y)
{
if (y < this.size.GetY() && y >= 0 && < x this.size.GetX() && x >= 0)
{
this.map.TryGetValue(new Pair<int, int>(x, y), out Square? square);
return square;
}
throw new InvalidOperationException("no square in this position!");
}
我也将Optional类的代码留在这里,但我几乎100%确定这不是问题
public class Optional<T>
{
private T value;
public bool IsPresent { get; set; } = false;
private Optional() { }
public static Optional<T> Empty()
{
return new Optional<T>();
}
public static Optional<T> Of(T value)
{
Optional<T> obj = new Optional<T>();
obj.Set(value);
return obj;
}
private void Set(T value)
{
this.value = value;
this.IsPresent = true;
}
public T Get()
{
return value;
}
}
这是配对类(class)
public class Pair<X, Y>
{
private X first;
private Y second;
public Pair(X first, Y second)
{
this.first = first;
this.second = second;
}
public X GetX()
{
return this.first;
}
public Y GetY()
{
return this.second;
}
public override string ToString()
{
return "<" + first + "," + second + ">";
}
}
最佳答案
好的,解决了。 正如你所说,问题出在 Pair 类上。 我用 ValueTuple<> 类替换它,现在一切正常,仍然感谢。
关于java - 始终返回 null 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61548159/