2017-03-17 73 views
0

为什么我这样做:C#阵列本身循环

所以我试图让一个游戏叫皇家冲突的应用程序,赢得比赛后,有你得到一个“随机”的胸部,这实际上并不是随机的......当你创建你的账户时,你会得到一个从0到239分配给你的数字,然后它会遵循胸部下降的模式。我正在制作的应用程序会接受用户的输入并将其与该模式进行比较,从而能够预测更高质量的下一个箱子下降的时间。

帮助我需要的代码:

是否有可能使一个数组类型的...内循环本身..因此,通过在一个循环中去阵例如,当,当“我“是239,然后加+1就会回到开头或#0(不一定是限制)。

类(和它的,我想循环容器):

class Chest 
    { 
     public int ID { get; set; } 
     public string Type { get; set; } 

     public Chest() 
     { 

     } 
     public Chest(int id, string type) 
     { 
      ID = id; 
      Type = type; 
     } 
    } 
class ChestContainer 
    { 
     private Chest[] ChestList = new Chest[240]; 
     public int Count { get; set; } 

     public ChestContainer(int size) 
     { 
      ChestList = new Chest[size]; 
     } 
     public void Add(Chest chest) 
     { 
      ChestList[Count++] = chest; 
     } 
     public Chest Get(int index) 
     { 
      return ChestList[index]; 
     } 
    } 

也不会介意任何提示,以提高我的类/容器类,目前这就是我一直在做我的整个“职业生涯”,因为这是我们在uni中的想法(减去班级的字符串重写)。

+2

看看模块化算术 – BradleyDotNET

回答

1

你可以使用Modulo %为了得到一个循环类的东西。

如果您将Container.Add方法替换为下面的方法,那么索引将会“重置”(缺少更好的单词)。

public void Add(Chest chest) 
{ 
    ChestList[Count++%(ChestList.Length)] = chest; 
} 

更新方法后,如果你想要一个例子,你可以试试下面的代码:

var container = new ChestContainer(240); 

for (int i = 0; i < 1000; i++) 
    container.Add(new Chest(i, $"{i}")); 

编辑为了有Get方法的工作,以及,修改它提到将确保您的容器按预期工作如下:

public Chest Get(int index) 
{ 
    return ChestList[index%(ChestList.Length)]; 
} 

为了测试它,你可以使用下面的代码:

var container = new ChestContainer(240); 

for (int i = 0; i < 1000; i++) 
{ 
    container.Add(new Chest(i, $"{i}")); 
    var value = container.Get(i); 
} 
+0

该死的是完整的软件包:D当我有权访问拥有代码的计算机时,我会对它进行测试,并在出现问题时回复此答案。队友的欢呼声! – ProgrammingStudent

0

您可以重载[]运算符来定义它的行为。

事情是这样的:

public static Chest operator [] (int index) { 
    return ChestList[index%240]; 
} 
0
public Chest Get(int index) 
{ 
    return ChestList[index%240]; //put your limit here 
} 

它是如何工作:%是模运算符。 它返回devision的其余部分。 示例: 5/2 = 2,剩下的1 => 5%2 = 1

在你的情况,被输入比239更高的数字时,与模它只是环绕。