我在调用方法时遇到麻烦。我有2个单独的文件。当用户键入S时,我的另一个文件中的shake方法将被调用。因此,当用户得到答案时,它将是随机的。
我对如何将该方法引入另一个文件感到困惑。下面是两个文件。
Program.cs:
static void Main(string[] args)
{
Console.WriteLine("Main program!");
Console.WriteLine("Welcome to the Magic 8 Ball");
Console.WriteLine("What would you like to do?");
Console.WriteLine("(S)hake the Ball");
Console.WriteLine("(A)sk a Question");
Console.WriteLine("(G)et the Answer");
Console.WriteLine("(E)xit the Game");
Magic8Ball_Logic.Magic8Ball ball = new Magic8Ball_Logic.Magic8Ball();
string input = Console.ReadLine().ToUpper();
public static string userAnswer = "";
do
{
if (input == "S")
{
if (userAnswer != null)
{
Console.WriteLine("Searching the Mystic Realms(RAM) for the answer");
}
else
{
//Call Method Shake()
}
}
else if (input == "A") {
userAnswer = Console.ReadLine();
}
else if (input == "G") {
//Call Method GetAnswer()
}
} while (input != "E");
}
Magic8Ball.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Magic8Ball_Logic
{
public class Magic8Ball
{
private List<string> _answers;
private int _currentIndex;
private string randomString;
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 20 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);
randomString = _answers[index];
}
public string GetAnswer()
{
//using the index picked by shake to return the answer
//return "";
return randomString;
}
public int AnswerCount
{
get { return _answers.Count; }
}
/* public override string ToString()
{
foreach (var el in _answers)
{
return el;
}
}*/
}
}
答案 0 :(得分:1)
首先,您必须创建此类的对象,然后调用该方法。
**Edit**
ball.Shake();
答案 1 :(得分:0)
如此处所写:https://stackoverflow.com/a/55986849/10128127
您的Program.cs应该更新为:
//使用
调用方法Shake() ball.Shake();
//通过
调用方法GetAnswer() ball.GetAnswer();