从课堂中挑选随机对象

时间:2016-10-24 11:27:51

标签: c# class if-statement random

所以我从班级Player

制作了这些对象
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制作的对象 (不要担心任何这些中的价值观,对于那些不知道的人来说,只是足球相关的东西)

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语句中比较他们的价值观。截至目前,我已将所有这些内容放在arrays

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

2 个答案:

答案 0 :(得分:2)

处理此问题的一种方法是在您的分会和播放器类中使用静态列表,该列表将填充程序创建的不同实例。通过在列表中添加新创建的实例,可以在类的构造函数中填充此列表。

例如,对于您的Player类,您将拥有:

public class Player
{
    // Static list keeping all your instances
    public static List<Player> players = new List<Player>();

    // Constructor
    public Player(/* Your different parameters */)
    {
        // Your class initialization

        players.Add(this);
    }

    // Rest of your class definition
}

然后你可以选择。您可以在类中添加一个静态方法来获取此列表的随机元素,如下所示:

public static Player GetRandomPlayer()
{
    Player player = players[randomnumber.Next(players.Length)];

    return player;
}

或者只需在代码中调用它:

Player player = Player.players[randomnumber.Next(Player.players.Length)];

最后,如果您也为俱乐部课程应用相同的想法,那么您的if语句将如下所示:

Player player = Player.GetRandomPlayer();
Club club = Club.GetRandomClub();

if (player.ability >= club.clubrating || player.potential >= club.clubrating)
{
    // What you want to do at that point
}

答案 1 :(得分:1)

例如,如果您将ClubPlayer个对象放在List中,则可以执行此操作:

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
}

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

这样,您只需将新的ClubPlayer对象填充到相应的列表中,而不必更改其余代码。