在foreach循环中为对象分配值

huangapple go评论82阅读模式
英文:

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 &lt; 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();

huangapple
  • 本文由 发表于 2020年1月3日 14:44:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/59574276.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定