编程语言
首页 > 编程语言> > c#-从类中选择随机对象

c#-从类中选择随机对象

作者:互联网

因此,我已经从班级玩家那里制作了这些对象

Player Silva = new Player("André Silva", 2, 5);
Player Moses = new Player("Victor Moses", 3, 3);
Player Batshuayi = new Player("Michy Batshuayi", 3, 4);
Player Medel = new Player("Gary Medel", 4, 4);

然后我有班级俱乐部制作的物品
(不要担心其中任何一个的价值,只为那些不认识的人提供足球相关的东西)

Club Barcelona = new Club("FC Barcelona", 5);
Club RealMadrid = new Club("Real Madrid", 5);
Club Inter = new Club("Inter", 4);
Club Liverpool = new Club("Liverpool", 4);

无论如何,我想让一名球员和一家具乐部低迷,并在if语句中比较它们的值.截至目前,我已经将所有这些放入数组

int[] Playerability = {Silva.ability,Moses.ability,Batshuayi.ability,Medel.ability};
int[] Clubrating = { Barcelona.clubrating, RealMadrid.clubrating, Inter.clubrating};

所以我可以使用简单的随机变量并将该变量放入数组中

int randomclub = randomnumber.Next(16);
int randomplayer = randomnumber.Next(28);

if (Playerability[randomplayer] >= Clubrating[randomclub] ||
    Playerpotential[randomplayer] >= Clubrating[randomclub])

但是如果我想要更多的对象,这似乎没有什么效果,所以我想知道是否有更简单的解决方案?抱歉,如果它很明显,但我似乎找不到它.语言是c#btw

解决方法:

例如,如果将“俱乐部”和“玩家”对象放在“列表”中,则可以执行以下操作:

var listOfPlayers = new List<Player>() { Silva, Moses }; 
var listOfClubs = new List<Club>() { Barcelona, RealMadrid };

var randomPlayer = listOfPlayers[randomnumber.Next(listOfPlayers.Length)];
var randomClub = listOfClubs [randomnumber.Next(listOfClubs.Length)];

if (randomPlayer.ability >= randomClub.clubrating || 
    randomPlayer.potential >= randomClub.clubrating)
{
    //Do your stuff
}

如果将对象放入数组,则同样有效.关键是您可以使用对象,而不能将对象的属性存储到新数组中.

这样,您只需将新的Club和Player对象填充到适当的列表中,而不必更改其余代码.

标签:if-statement,random,c,class
来源: https://codeday.me/bug/20191118/2025076.html