有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

总是返回null的java方法

我被一段从Java翻译成C的代码卡住了

基本上,我有一个Map(Dictionary),其中的键由Pair和由我创建的类(Square)表示的值组成;在这个类中只有一个字段是可选的(是的,我用C#创建了可选类)

在开始的时候,我用对填充这个字典,以使一个simil网格和空可选,正如您在下面的代码中看到的那样

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()));
        }
    }
}

这是方形类

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。当我试图从字典中获取一个存在的值时,它抛出了系统。NullReferenceException:对象引用未设置为对象的实例。 在这段代码中,我去掉了所有的控件,但我知道我试图得到一个已经插入的值;此外,我还试着查字典。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!");
}

我在这里也留下了可选类的代码,但我几乎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;
    }
}

这是双人课

    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 + ">";
        }
    }

共 (1) 个答案

  1. # 1 楼答案

    好的,解决了。 正如你所说,问题在于结对班。 我用ValueTuple替换它<&燃气轮机;上课了,现在一切都好了,还是谢谢你