【问题标题】:Inheritance - storing objects list<class> with loops C#继承 - 使用循环 C# 存储对象 list<class>
【发布时间】:2015-04-21 16:13:53
【问题描述】:

在 C# 基础课程中,我遇到了一个练习,这对于我即将到来的期末考试来说非常重要。

我有一个无法用语言描述的问题。因此,我将向您展示代码,然后您可能会帮助我。 我一直被困在这个问题上,无法解决它,很长一段时间。因为那个,我不想要任何复制粘贴代码。我想了解它。所以请告诉我我失败的地方。

解释我想做什么。 我想创建一个 飞镖游戏 501。因此,首先我添加玩家,他们投掷飞镖,在每回合后公布分数,然后当一名玩家达到 501 分时,游戏宣布获胜者和他的所有掷球

我解决这个问题的想法是有一个添加播放器循环,它终止(我已经解决了这个问题)。 完成创建玩家(列表元素)后,您将使用 foreach 循环执行方法,运行玩家列表中的所有玩家,一次执行一个对象,最后 这是我真正的问题: 将他们所有的 scores 存储在另一个 list 中。

我们来看看代码

列表

private List<Player> players = new List<Player>();  //This list is fine

这是循环

foreach (Player dartThrows in players) //My loop
             {
               dartThrows.DoThrow();
               dartThrows.GetScore();
             }

SubClass1(命名为玩家

public List<Darts> dartList = new List<Darts>(); //<--HERE IS THE PROBLEM

只是一些随机的构造函数和方法。

抛出方法。这不是问题,但我把它写下来给你一个想法

public void DoThrow()
            {
                           var tries = 3;

        for (int i = 0; i < tries; i++) 
        {
             //No problems here just int read-user input data
        }
AddDarts(int a, int b, intc)

    }

这就是我所有的问题,如果能得到解决,我的生活会轻松很多。

        public void AddDarts(Darts toDartList) 
    {

        dartList.Add(toDartList); 
    }

子类2(飞镖

这是我的构造函数

private int dartOne;
private int dartOne;
private int dartOne;

这是我的方法

        public Darts(int DartOne, int DartTwo, int DartThree) 
    {
        dartOne = DartOne;
        dartTwo = DartTwo;
        dartThree = DartThree;

    }

最好的问候马库斯·约翰逊

这是我的完整程序

class Program
{
    static void Main(string[] args)
    {
        Game game = new Game();
        game.PlayGame();
    }
}
class Game
{

    private List<Player> players = new List<Player>();
    private List<Player> computers = new List<Player>();

    public void AddPlayer(string newPlayers)
    {
        players.Add(new Player(newPlayers));
    }
    public void AddComputer(string newComputer) 
    {
        computers.Add(new Player(newComputer));
    }
    static string UpperCaseFirst(string s)
    {
        if (string.IsNullOrEmpty(s))
        {
            return string.Empty;
        }
        return char.ToUpper(s[0]) + s.Substring(1);
    }
    public void PlayGame() 
    {
        bool noWinner = false;
        bool stopLoop = false;

        Console.WriteLine("<<<WELCOME TO DART 501>>>");

        Console.WriteLine("\nPress [S] to start game!");
        Console.Beep();
        Console.ReadLine();
        Console.Clear();

        do
        {
            Console.WriteLine("Enter name of players and type [D]ator for adding NPC\nType [S]top to start the game");
            string addPlayer = Console.ReadLine();
            string FirstUpperLetter = UpperCaseFirst(addPlayer);
            if (FirstUpperLetter == "Stop" || FirstUpperLetter == "S")
            {
                stopLoop = true;
            }
            if (FirstUpperLetter == "D" || FirstUpperLetter == "Dator")
            {
                string computer = FirstUpperLetter;
                AddComputer(computer);
            }
            else
            {
                AddPlayer(FirstUpperLetter);
            }

        } while (stopLoop == false) ;
        players.RemoveAt(players.Count - 1);

        do 
        {
            Console.Clear();

            foreach (Player arrowThrows in players)
            {
                noWinner = true;
                Console.WriteLine("\n~~~Starting Round~~~~");
                arrowThrows.DoThrow();
                Console.WriteLine("This round you got {0}", arrowThrows.CalculatePoints());
                if (arrowThrows.Score > 501)
                {
                    Console.Clear();
                    Console.WriteLine("<<<WE HAVE A WINNER>>>");
                    System.Threading.Thread.Sleep(500);
                    Console.WriteLine("...The winner is: ");
                    System.Threading.Thread.Sleep(1000);
                    Console.WriteLine("{0} He made these epic throws: ", arrowThrows.Name);
                    foreach(Arrows finalResult in arrowThrows.arrowList)
                    {
                        Console.WriteLine(finalResult);
                        Console.ReadLine();
                    }
                    noWinner = false;
                }

            }
            foreach (Player computerThrows in computers)
            {
                computerThrows.RandomThrow();
                System.Threading.Thread.Sleep(500);
            }
        }while(noWinner == true);

    }

}
class Player
{
    public List<Arrows> arrowList = new List<Arrows>();
    public List<int> ScoreBoard = new List<int>();

    public Player() { }

    public int Score { get; set; }

    public Player(int score)
    {
        Score = score;
    }

    public string Name { get; set; }

    public Player(string name) 
    {
        Name = name;
    }
    public int RoundScore { get; set; }
    public void RandomThrow() 
    {
        Random rndComp = new Random();

        Console.WriteLine("...Loading Npc_throw.exe");
        System.Threading.Thread.Sleep(300);
        int random1 = rndComp.Next(0, 60);
        System.Threading.Thread.Sleep(300);
        int random2 = rndComp.Next(0, 60);
        System.Threading.Thread.Sleep(300);
        int random3 = rndComp.Next(0, 60);

        Console.WriteLine("Random computer got this random score {0}", random1 + random2 + random3);
        arrowList.Add(new Arrows(random1, random2, random3));
    }

    public void DoThrow() 
    {
        Console.WriteLine("###{0} make your throws###", Name);
        var tries = 3;

        for (int i = 0; i < tries; i++) 
        {
            Console.WriteLine("\nEnter score for {0} arrow", i + 1);
            string arrowScore = Console.ReadLine();
            int addScore = int.Parse(arrowScore);

            while(-1 > addScore || 61 < addScore) 
            {

                Console.WriteLine("\nInvalid score! Enter a score between 0-60/n<<<You may type [R]andom or [R] for a random score>>>");
                arrowScore = Console.ReadLine().ToUpper();

                if (arrowScore == "R" || arrowScore == "RANDOM")
                {
                    Random rnd = new Random();
                    addScore = rnd.Next(0, 60);
                    goto start;
                }
                else
                {
                    addScore = int.Parse(arrowScore);
                }

            }

        start:
        ScoreBoard.Add(addScore);
        }
        ScoreBoard.ToArray();

        arrowList.Add(new Arrows(ScoreBoard[0],ScoreBoard[1], ScoreBoard[2]));
    }
    public int CalculatePoints() 
    {
        Score = ScoreBoard.Sum();
        return Score;
        }
    public void AddArrows(Arrows toArrowList) 
    {
        toArrowList.ToString();
        arrowList.Add(new Arrows(ScoreBoard[0], ScoreBoard[1], ScoreBoard[2])); 
    }
}
class Arrows 
{
    private int arrowOne;
    private int arrowTwo;
    private int arrowThree;

    public int score { get; set; }

    public Arrows(int ArrowOne, int ArrowTwo, int ArrowThree) 
    {
        arrowOne = ArrowOne;
        arrowTwo = ArrowTwo;
        arrowThree = ArrowThree;

    }
    public int GetScore() 
    {
        return arrowOne + arrowTwo + arrowThree;
    }
    public override string ToString()
    {
        return string.Format("{0}-1:st arrow: {1}-2:nd arrow: {2}- 3:rd arrow: {3}", GetScore(), arrowOne, arrowTwo, arrowThree);
    }
}

}

【问题讨论】:

  • TL;DR...您说“这里有问题”...但您永远不会清楚地知道“问题”是什么...标题还包含首先不存在的“多重继承”在 C# 中,据我所知,甚至从未在帖子中提及。
  • 最好从尝试运行程序时遇到的错误开始,或者运行程序时发生的意外行为,引发异常的相关代码或有一个逻辑错误,以及你打算做什么。
  • 什么是 dartOne、dartTwo、dartThree?
  • 我希望我知道问题出在哪里,这样我就可以更具体了。没有错误或任何类似的事情。问题是*在子类中的另一个列表 中存储值 并使用循环 这样做。 dartOne, dartTwo, dartThree 是我的老师告诉我实现的对象。
  • 请将此仅视为建设性的批评。如果在考试开始时您还没有掌握课程的核心基础知识,那么您就不应该通过考试。

标签: c# list constructor multiple-inheritance


【解决方案1】:

您的方法的问题在于您使用了List。这个集合没有唯一的信息,只是一组数据。我会推荐TupleDictionaryKeyValuePair 或干净的数据模型

没有要求的方法可能不可行。您的问题源于与持久性相关的问题。您的多重继承标题也不正确,C# 只允许继承单个 class

我可能会做的是:

public class Player
{
     public string Name { get; set; }
     public string Throw { get; set; }
     public string Points { get; set; }
}

这样做是非常有益的。上面的class 代表一个特定的Model。当您的方法被调用时,您将应用所述结果。然后,当您计算分数时,您会针对特定人员或所有人遍历 List&lt;Player&gt; 并显示输出。

我不打算写你的应用程序,但可以这样想:

  1. 玩家注册
  2. 玩家回合
  3. 球员投掷
  4. 比赛得分
  5. 存储播放器结果
  6. 重复步骤二到五,三遍。
  7. 显示输出:球员、投掷、得分和总分

通过使用该模型,您可以掌握结果的相关信息。这个概念对于面向对象编程很重要。

【讨论】:

  • 非常感谢您!我会详细阅读您提到的内容并实施您的解决方案。
【解决方案2】:

您可以使用字典来保存每个玩家的分数

Dictionary<Player, List<int>> playerScores = new Dictionary<Player, List<int>>();

playerScores.Add(player1, new List<int>()); //init dictionary with a new player
playerScores[player1].Add(number); //add a value to the list associated with the player

所以每个玩家都有一个分数列表。

【讨论】:

  • 非常感谢。我也会试试这个并在对象上查找更多信息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-04
  • 1970-01-01
相关资源
最近更新 更多