public class MathProblem
{
public virtual void setproblem()
{
Random random = new Random();
int num1 = random.Next(100);
int num2 = random.Next(100);
int sum = num1 + num2;
}
public virtual void askuserforanswer()
{
int answer;
Console.WriteLine("Enter your answer");
answer = Convert.ToInt32(Console.ReadLine());
}
public virtual void displayproblem()
{
Console.WriteLine( num1.ToString() + " + " + num2.ToString() + " = ?");
}
}
我想将 num1 和 num2 从 setproblem 方法调用 displayproblem 方法。我不知道该怎么做。
请帮助......
答案 0 :(得分:2)
你不能。在方法内声明的变量只能在该方法中使用。为了能够在整个班级中使用它们,您必须在班级声明它们:
public class MathProblem
{
private Random random = new Random();
private int num1, num2, sum;
public virtual void SetProblem()
{
num1 = random.Next(100);
num2 = random.Next(100);
sum = num1 + num2;
}
public virtual void AskUserForAnswer()
{
int answer;
Console.WriteLine("Enter your answer");
answer = Convert.ToInt32(Console.ReadLine());
}
public virtual void DisplayProblem()
{
Console.WriteLine( num1.ToString() + " + " + num2.ToString() + " = ?");
}
}
此外,请注意我已根据Microsoft Capitalization Conventions.
将方法名称更改为Pascal大小写答案 1 :(得分:0)
你必须使用字段。
public class MathProblem
{
int num1;
int num2;
public virtual void setproblem()
{
Random random = new Random();
num1 = random.Next(100);
num2 = random.Next(100);
int sum = num1 + num2;
}
public virtual void askuserforanswer()
{
int answer;
Console.WriteLine("Enter your answer");
answer = Convert.ToInt32(Console.ReadLine());
}
public virtual void displayproblem()
{
Console.WriteLine( num1.ToString() + " + " + num2.ToString() + " = ?");
}
}
答案 2 :(得分:0)
您可以使用类级别的字段:
public class MathProblem
{
int num1;
int num2;
... rest of code unchanged
}
如果你需要在课外使用这些,你可以使用以下属性:
public class MathProblem
{
public int num1 { get; private set;}
public int num2 { get; private set;}
... rest of code unchanged
}
或者,如果您希望能够从课外设置它们:
public class MathProblem
{
public int num1 { get; set;}
public int num2 { get; set;}
... rest of code unchanged
}
还有一些提示: