英文:
Assigning values to objects in a foreach loop
问题
如何在foreach
循环中为对象分配值。
以下是代码:
using System;
namespace WorkingWithClasses
{
class Program
{
static void Main(string[] args)
{
//创建5个玩家对象
Player[] players = new Player[5];
//为玩家分配值会引发空引用异常错误:
foreach(Player player in players)
{
player.Skill = 5;
}
float skillSum = 0;
foreach(Player player in players)
{
skillSum += player.Skill;
}
Console.WriteLine(skillSum);
}
}
class Player
{
public float Skill { get; set; }
}
}
希望这对你有所帮助!
英文:
How to assign values to objects in foreach
loop.
Code is below:
using System;
namespace WorkingWithClasses
{
class Program
{
static void Main(string[] args)
{
//create 5 player objects
Player[] players = new Player[5];
//assigning a value to a player brings null reference exception error:
foreach(Player player in players)
{
player.Skill = 5;
}
float skillSum = 0;
foreach(Player player in players)
{
skillSum += player.Skill;
}
Console.WriteLine(skillSum);
}
}
class Player
{
public float Skill { get; set; }
}
}
答案1
得分: 3
在你的玩家数组中,每个“Player”都没有被初始化。尝试使用这个for循环,而不是在你获取null引用的foreach循环中:
for (var i = 0; i < players.Length; i++)
{
players[i] = new Player() { Skill = 5 };
}
你也可以使用这个方法,不过它比使用for循环遍历数组要慢:
using System.Linq;
players = Enumerable.Repeat(new Player() { Skill = 5 }, 5).ToArray();
英文:
Every "Player" in your players array is not initialized. Try with this for loop instead of the foreach loop where you are getting the null reference:
for (var i = 0; i < players.Length; i++)
{
players[i] = new Player() { Skill = 5 };
}
You can also use this, however it's slower than iterating through the array with a for loop:
using System.Linq;
players = Enumerable.Repeat(new Player() { Skill = 5 }, 5).ToArray();
答案2
得分: 0
请将 Player[] players = new Player[5];
替换为 Player[] players = Enumerable.Repeat(new Player(), 5).ToArray();
。
英文:
You need to initialize your players instance object since you are creating array holder.
Replace Player[] players = new Player[5];
with
Player[] players = Enumerable.Repeat(new Player(), 5).ToArray();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论