在foreach循环中为对象分配值
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在foreach循环中为对象分配值相关的知识,希望对你有一定的参考价值。
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 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; }
}
}
答案
播放器数组中的每个“玩家”都没有初始化。尝试使用此for循环而不是要获取空引用的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();
另一答案
您尚未初始化播放器类,请尝试以下以获得预期的结果。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System;
namespace WorkingWithClasses
{
class Program
{
static void Main(string[] args)
{
//create 5 player objects
//Player[] players = new Player[5];
List<Player> playersList = new List<Player>() {
new Player
{
Skill = 5
},
new Player
{
Skill = 5
},
new Player
{
Skill = 5
},
new Player
{
Skill = 5
},
new Player
{
Skill = 5
}
};
//assigning a value to a player brings exception error:
/* foreach (Player player in playersList)
{
player = new Player();
} */
float skillSum = 0;
foreach (Player player in playersList)
{
skillSum += (float)player.Skill;
}
Console.WriteLine(skillSum);
Console.WriteLine();
}
}
class Player
{
public float? Skill { get; set; }
}
}
以上是关于在foreach循环中为对象分配值的主要内容,如果未能解决你的问题,请参考以下文章
使用Kotlin中的foreach循环遍历BigInteger值
我们如何在 laravel php 刀片模板中为 foreach 循环定义循环变量