如何调用具有3个输出的函数?

时间:2014-02-21 02:54:32

标签: c#-4.0

我创建了一个带有3个返回值的方法,但问题是如何调用此方法并将其分配给3个变量?

 public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }


    private void Form1_Load(object sender, EventArgs e)
    {

    }

    public void  random(out int num1, out int num2,out int num3)
    {

        int number1,number2,number3;
            Random ranNum = new Random();
            number1 = ranNum.Next(1, 7);
            number2 = ranNum.Next(1, 7);
            number3 = ranNum.Next(1, 7);

            num1 = number1;
            num2 = number2;
            num3 = number3;

    }

}

2 个答案:

答案 0 :(得分:0)

在调用方法(返回void)之前声明变量并将它们作为out参数传递。或者,您可以创建另一个类或内部类,它将值作为属性并从方法返回该实例。

 int num1;
 int num2;
 int num3;

 random(out num1, out num2, out num3);

public class RandomNumbers
{
    public int Num1 { get; set; }
    public int Num2 { get; set; }
    public int Num3 { get; set; }
}

...

public RandomNumbers random()
{
    Random ranNum = new Random();

    return new RandomNumbers
    {
        Num1 = ranNum.Next(1, 7),
        Num2 = ranNum.Next(1, 7),
        Num3 = ranNum.Next(1, 7),
    };

}

你可以做的另一件事是返回一个Tuple - 虽然我倾向于认为这种语法通常很难使用,而且更喜欢特定的容器类型,具有更多语义含义。

public Tuple<int,int,int> random()
{
    Random ranNum = new Random();

    return Tuple.Create(ranNum.Next(1, 7), ranNum.Next(1, 7), ranNum.Next(1, 7));
}

答案 1 :(得分:0)

像这样:

private void Form1_Load(object sender, EventArgs e)
{
    int n1, n2, n3
    random(out n1, out n2, out n3);
    // now n1, n2 and n3 has the output values
}

由于输出参数不是最佳实践,因此您可以更好地创建Result类,并仅在 random 函数中返回一个对象:

public class RandomResult
{
    public int n1 { get;set;}
    public int n2 { get;set;}
    public int n3 { get;set;}
}

public RandomResult random()
{
    RandomResult result = new RandomResult();
    Random ranNum = new Random();
    result.n1 = ranNum.Next(1, 7);
    result.n2 = ranNum.Next(1, 7);
    result.n3 = ranNum.Next(1, 7);
    return result;
}

private void Form1_Load(object sender, EventArgs e)
{
    RandomResult result = random();
    // now RandomResult.n1, RandomResult.n2 and RandomResult.n3 has the output values
}