简体   繁体   English

如果类实例在数组中,我可以列出一个数字吗?

[英]Can I list a number if class instances in an array?

I am just starting out with learning C#, and to practice I am trying to create a hangman game (guess letters of a word).我刚开始学习 C#,为了练习我正在尝试创建一个刽子手游戏(猜单词的字母)。

I created a class WordToGuess and created multiple instances of this class, one for each word.我创建了一个 WordToGuess 类并创建了该类的多个实例,每个单词一个。

Now I would like to randomly pick one of these instances to be guessed by the player.现在我想随机选择这些实例之一供玩家猜测。 I am not sure how to approach this.我不知道如何解决这个问题。

I found code to randomly pick an index from an array, which seems to be a good way to do it.我找到了从数组中随机选择一个索引的代码,这似乎是一个很好的方法。 But now I don't know what exactly I can do.但现在我不知道我到底能做什么。 Can I list instances in an array?我可以在数组中列出实例吗? And if not, how can I elegantly do it otherwise.如果没有,我怎么能优雅地做到这一点。 I can think of a workaround, but that's not the point of the exercise.我可以想到一个解决方法,但这不是练习的重点。

Example of my instance:我的实例示例:

WordToGuess duck = new WordToGuess();
duck.numberOfLetters = 4;
duck.theWord = "Duck";
duck.theLetters = new string[] { "d", "u", "c", "k" };
duck.difficulty = "easy";
duck.wordID = "e3";

My random generation attempt (I thought I could just generate the string ID and then address the instance that way, I think I didn't think that through though)我的随机生成尝试(我以为我可以只生成字符串 ID,然后以这种方式处理实例,但我想我不这么认为)

string[] easyWords = new string[] { "e1", "e2", "e3", "e4", "e5", "e6", "e7" };
Random rndE = new Random();
int indexE = rndE.Next(easyWords.Length);

There are many ways to do what you want.有很多方法可以做你想做的事。 Maybe one of the best would be to store the WordToGuess instances in a Dictionary<string, WordToGuess> where the key is that identifier.也许最好的方法之一是将WordToGuess实例存储在Dictionary<string, WordToGuess> ,其中键是该标识符。

But i would also refactor your class, some properties are not needed like the string[] for the letters, since string already implements IEnumerable<char> .但我也会重构你的类,不需要一些属性,比如字母的string[] ,因为 string 已经实现了IEnumerable<char> I would also make that Diffciculty an enum instead of a string and provide a constructor for WordToGuess that takes the most important properties as input:我还将使 Diffciculty 成为enum而不是string并为WordToGuess提供一个构造函数,该构造函数将最重要的属性作为输入:

public class WordToGuess
{
    public enum GuessDifficulty 
    {
        Easy, Medium, Hard      
    }
    
    public WordToGuess(string word, string id, GuessDifficulty difficulty)
    {
        TheWord = word;
        ID = id;
        Difficulty = difficulty;
    }

    public string ID {get;set;}
    public string TheWord {get;set;}
    public GuessDifficulty Difficulty {get;set;}
}

Now you can initialize and fill the dictionary in this way:现在你可以用这种方式初始化和填充字典:

Dictionary<string, WordToGuess> wordDictionary = new Dictionary<string, WordToGuess>();
WordToGuess duck = new WordToGuess("Duck", "e3", WordToGuess.GuessDifficulty.Easy);
wordDictionary.Add(duck.ID, duck);
// initializte and add more ...

Your random word logic then just tries to find the word with the Id in the dictionary:然后,您的随机单词逻辑只是尝试在字典中查找具有 Id 的单词:

string[] easyWords = new string[] { "e1", "e2", "e3", "e4", "e5", "e6", "e7" };
Random rndE = new Random();
int idIndex = rndE.Next(easyWords.Length);
WordToGuess randomWord = wordDictionary.TryGetValue(easyWords[idIndex], out WordToGuess w) ? w : null;

Note that it's null if there is not a word with that random identifier.请注意,如果没有带有该随机标识符的单词,则它为null

An example with arrays:数组示例:

class Program
    {
        static void Main(string[] args)
        {
            WordToGuess[] wtg = new WordToGuess[10];

            wtg[0] = new WordToGuess("Duck", "easy", "e3");
            wtg[1] = new WordToGuess("Dog", "easy", "e4");
            wtg[2] = new WordToGuess("House", "easy", "e5");
            wtg[3] = new WordToGuess("Pneumonoultramicroscopicsilicovolcanoconiosis", "difficult", "e6");
            Console.WriteLine();

            foreach (var item in wtg)
            {
                if (item is not null)
                {
                    Console.WriteLine($"{item.wordID}, {item.theWord}, {item.difficulty}, {item.numberOfLetters}");
                }
                
            }
            Console.WriteLine();

            Random r = new Random();
            WordToGuess randomWord = wtg[r.Next(0, 3)];
            Console.WriteLine($"A random word: {randomWord.wordID}, {randomWord.theWord}, {randomWord.difficulty}, {randomWord.numberOfLetters}");

            // this needs: using System.Linq;
            randomWord = wtg.Where(x => x is not null).OrderBy(x => r.Next()).First();
            Console.WriteLine($"Another random word: {randomWord.wordID}, {randomWord.theWord}, {randomWord.difficulty}, {randomWord.numberOfLetters}");

            Console.ReadLine();

        }
    }

    public class WordToGuess
    {
        public int numberOfLetters { get; set; }
        public string theWord { get; set; }
        public char[] theLetters { get; set; }
        public string difficulty { get; set; }
        public string wordID { get; set; }

        public WordToGuess()
        {}
        public  WordToGuess(string theWord, string difficulty, string wordID)
        {
            this.numberOfLetters=theWord.Length;
            this.theWord=theWord;
            this.theLetters=theWord.ToUpper().ToCharArray();
            this.difficulty=difficulty;
            this.wordID=wordID;
        }
    }

output like this:输出如下:

e3, Duck, easy, 4
e4, Dog, easy, 3
e5, House, easy, 5
e6, Pneumonoultramicroscopicsilicovolcanoconiosis, difficult, 45

A random word: e4, Dog, easy, 3
Another random word: e5, House, easy, 5

The word Pneumo....iosis was found here: https://irisreading.com/10-longest-words-in-the-english-language/ Pneumo....iosis 这个词是在这里找到的: https : //irisreading.com/10-longest-words-in-the-english-language/

Make a List and add all instances to the list.创建一个列表并将所有实例添加到列表中。 Then use that random index code on the list.然后在列表中使用该随机索引代码。 In C# we rarely use [] and instead use lists.在 C# 中,我们很少使用 [],而是使用列表。 (Yes you can have object instances in an array) (是的,您可以在数组中拥有对象实例)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM