c# - 如何从方法中发送和检索

标签 c# wpf xaml

我正在尝试发送和检索值,因为我的代码是面向对象的,在 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/

相关文章:

c# - 代码有点困惑

wpf - WPF 应用程序的 "Enable Application Framework"是什么意思?

c# - 具有相同 xaml 文件和不同 DataContext 的多个输入表单

c# - 获取花括号之间的值c#

c# - 在紧凑的框架中以多种形式提供变量

c# - Adorner 会破坏 MVVM 吗?

wpf - 通过 ViewModel 绑定(bind)到 DependencyProperty 无效

c# - 从 Excel VSTO 和 Win Form 运行 WPF 应用程序

c# - WPF TextBlock 绑定(bind)到字符串

c# - 从图片框保存图像,图像由图形对象绘制