C#保存多个值

标签 c#

我有一个类:

class Entity
{
    private String question;
    private String answer;
    private static int length;

    Crosswords cr = new Crosswords();

    public Entity(int posX, int posY, int direction)
    {
        length = cr.getSpaceLength(posX, posY, direction);
    }

    public int getLength()
    {
        return length;
    }
}

在另一个类中,我创建了一个这样的实体数组:

Entity[] et = new Entity[100];

然后我有一个计算长度的算法,我想保存每个实体的长度,但在那之后,当我这样做时:

for(int i=0; i<100; i++)
    Console.WriteLine(et[i].getLength());

我为所有实体设置了相同的长度(最后一个实体的长度),但我为它们设置了不同的长度。为什么会这样?我必须做什么才能为每个实体保存不同的长度?

附言

我这样创建实体:

for(int i=0; i<100; i++)
    et[i] = new Entity(somevalueX, somevalueY, direction);

最佳答案

从长度中删除静态或更好地执行此操作,在需要时计算长度。

class Entity
{
    private String question;
    private String answer;
    private int _posX;
    private int _posY;
    private int _direction;
    Crosswords cr = new Crosswords();

    public Entity(int posX, int posY, int direction)
    {
        _posX = posX;
        _posY = posY;
        _direction = direction;
    }

    public int getLength()
    {
        return cr.getSpaceLength(_posX, _posY, _direction);
    }
}

关于C#保存多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28318010/

相关文章:

c# - 如何在启动时启动控制台应用程序(!)? C#

c# - 存储库应该通过构造函数注入(inject)还是包装在使用中?

c# - 具有非接口(interface)的构造函数参数的依赖注入(inject)

c# - Bitmap Stride 和 4 bytes 的关系?

c# - 将System.Drawing.Bitmap读入OpenCV/Emgu以查找轮廓

c# - asp.net mvc 5 DropDownList nullable int default option not null

c# - 报表查看器可以从表单传递图像吗?

c# - 在 Windows 控制台应用程序中使用 ax2012 服务

c# - 表达式静态方法需要空实例非静态方法需要非空实例

c# - 在 Linux Python 中使用 .NET Core 库