简体   繁体   English

如何从列表更新项目属性?

[英]How to update Item Property from list?

I have a generic list named mysoldier whose items has properties like height, weight etc. So after adding the soldiers (mysoldier.Add), I want to change the height of soldier. 我有一个名为mysoldier的通用列表,其项目具有高度,重量等属性。因此,在添加士兵(mysoldier.Add)之后,我想更改士兵的身高。 For that I used this: 为此,我使用了这个:

 public void Increase Height() 
 { 
  for (int i = 0; i < mysoldier .Count; i++)
  { 
   if (this.mysoldier [i].height > 7) 
   { 
     this.mysoldier [i].height= 7; 
   } 
   else 
   {
    this.mysoldier [i].height+= 1; 
   } 
  } 

but this is not changing height of only one specific object instead it changes height of all soldiers added to the container. 但这并不仅仅是改变一个特定物体的高度,而是改变添加到容器中的所有士兵的高度。

  public void IncreaseHeight(int i) //#, or mysoldier.Count - 1 (I believe) for last
  {
    if (this.mysoldier [i].height > 7) 
    { this.mysoldier [i].height= 7; } 
    else { this.mysoldier [i].height+= 1; }
  }

But with this code I change only the height of the soldier which is previously created. 但是使用此代码,我仅更改了先前创建的士兵的身高。 So please anyone can point me what is wrong in the code? 因此,请任何人都可以指出我代码中的错误吗?

Some tips: 一些技巧:

If it's a list, don't call it "mySoldier", call it "mySoldiers". 如果是列表,请不要将其称为“ mySoldiers”,而应将其称为“ mySoldiers”。 This can make you confuse. 这会使您感到困惑。 How are you creating these soldiers? 您如何创建这些士兵? Because... if you are creating then adding the same through a loop, you are adding the reference(memory address) to the list. 因为...如果要创建然后通过循环添加,则要将引用(内存地址)添加到列表中。 If you change something in one, you change in all of them. 如果您将某一项更改为一个,则全部更改。 If you just want to change the property for one specific item, just pass the index as a parameter to your function instead of using a for statement. 如果只想更改一个特定项目的属性,只需将索引作为参数传递给函数,而不要使用for语句。

If you still have the problem going on, Let's try to solve it. 如果问题仍然存在,请尝试解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM