我正在尝试发送和检索值,因为我的代码是面向对象的,在 Addition.xaml 中我试图发送“AddLevel”变量,它是一个 int,在 Addition.xaml 中我有:
private void pageRoot_Loaded(object sender, RoutedEventArgs e)
{
Methods.AddLevels(AddLevel, Question1,Question2, Answer);
QuestionText1.Text = System.Convert.ToString(Question1);
QuestionText2.Text = System.Convert.ToString(Question2);
}
在这个方法中,我试图将 AddLevel int 变量发送到 Methods 类以确定要做什么,在 Methods 类中我有:
public static int AddLevels(int AddLevel, int Question1, int Question2, int Answer)
{
Random rnd = new Random();
if(AddLevel == 0 || AddLevel == 1)
{
Question1 = rnd.Next(0, 10);
Question2 = rnd.Next(0, 10);
Answer = Question1 + Question2;
}
return Question1;
return Question2;
return Answer;
}
总而言之,我试图将 AddLevel 从 Addition.xaml 发送到方法类中的 AddLevels 方法,然后我试图从该方法中检索问题 1、问题 2 和答案。我该怎么做呢?
最佳答案
一种选择是使用元组
:
private void pageRoot_Loaded(object sender, RoutedEventArgs e)
{
Tuple<int, int, int> result = Methods.AddLevels(AddLevel, Question1, Question2, Answer);
QuestionText1.Text = System.Convert.ToString(result.Item1);
QuestionText2.Text = System.Convert.ToString(result.Item2);
}
public static Tuple<int, int, int> AddLevels(int addLevel, int question1, int question2, int answer)
{
if (addLevel == 0 || addLevel == 1)
{
Random rnd = new Random();
question1 = rnd.Next(0, 10);
question2 = rnd.Next(0, 10);
answer = question1 + question2;
}
return Tuple.Create(question1, question2, answer);
}
另一个不太推荐的选项是使用 ref
关键字:
private void pageRoot_Loaded(object sender, RoutedEventArgs e)
{
Methods.AddLevels(AddLevel, ref Question1, ref Question2, ref Answer);
QuestionText1.Text = System.Convert.ToString(Question1);
QuestionText2.Text = System.Convert.ToString(Question2);
}
public void AddLevels(int addLevel, ref int question1, ref int question2, ref int answer)
{
if (addLevel == 0 || addLevel == 1)
{
Random rnd = new Random();
question1 = rnd.Next(0, 10);
question2 = rnd.Next(0, 10);
answer = question1 + question2;
}
}
关于c# - 如何从方法中发送和检索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27831047/