c# - 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;
}
解决方案
使用您的原始代码:
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
。您可以参考其他线程。
推荐阅读
- php - html表格背景图像不起作用
- php - 将值动态存储到数组的另一种方法是使用不推荐使用的代码来执行相同的操作
- webrtc - DOMException: 无法启动视频源
- javascript - Object.assign() ,合并/覆盖键,复制数组的值以创建对象
- c# - 如何使用 Lambda 表达式 c# 在一个列表中为与另一个列表中的 Id 匹配的 Id 设置标志
- android - 如何解决使用 volley 解析登录 json 的问题?
- c# - 为已自动激活的 ComponentRegistration 添加激活事件
- php - office365 php中的批处理请求给出了错误的请求
- c# - 如何重新实现电子邮件的可扩展功能
- eclipse - 反编译器中的德语字符编码问题