首页 > 解决方案 > C# 从列表中返回一个随机字符串

问题描述

我写了一个列表,里面有一个问题的答案。我想使用我的 GetAnswer() 方法将当前答案作为字符串返回。

我遇到的问题是我无法得到我选择打印出来的随机答案。

namespace Magic8Ball_Logic
{

public class Magic8Ball
{
    private List<string> _answers;
    private int _currentIndex;
    public Magic8Ball()
    {
        _answers = new List<string>();
        _answers.Add("It is certain.");
        _answers.Add("It is decidedly so.");
        _answers.Add("Without a doubt.");
    }

    public Magic8Ball(List<string> answers)
    {
        //I won't use the default. Use the ones passed in.
        _answers = answers;
    }

    public void Shake()
    {
        //picking the index of the answer to show the user
        Random r = new Random();
        int index = r.Next(_answers.Count);
        string randomString = _answers[index];
    }

    public string GetAnswer()
    {
        //using the index picked by shake to return the answer
        return randomString;
    }

标签: c#random

解决方案


使用您的原始代码:

public void Shake()
{
    //picking the index of the answer to show the user
    Random r = new Random();
    _currentIndex = r.Next(_answers.Count);
}

public string GetAnswer()
{
    //using the index picked by shake to return the answer
    return _answers[_currentIndex];
}

您可能需要制作 Random static。您可以参考其他线程。


推荐阅读