C#函数返回两个值 [英] C# Function returning two values

查看:155
本文介绍了C#函数返回两个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想有一个功能,我将输入一个数组,因此我需要另一个阵列和一个整数值。这可能吗?

I would like to have a function in which I will input an array and as a result i need another array and an integer value. Is this possible?

例如:

private int[] FunctionName (int[] InputArray)
{
    //some function made here
    int intResult = xxxxx
    int[] array = xxxxx

    return intResult; //but here i need also to pass the new array!
}

编辑:

我需要的是以下(更新);

what i need is the following (updated);

我有一个功能,作为输入需要什么,但是在内部生成两个项目 - 阵列+整数。我需要返回这两个项目? 你也可以让我知道我怎么可以使用这个项目?

I have a function that as an input takes nothing, but internally generates two items - array + integer. I need to return these two items? Can you also let me know how can I then use this items?

这可怎么办呢?

推荐答案

您有几个选项(为了什么将是我的preference):

You have a couple of options (in order of what would be my preference):

创建一个类,并返回:

class MyResult
{
    public int[] Array { get; set; }
    public int Integer { get; set; }
}

...

private MyResult FunctionName(int[] inputArray)
{
    return new MyResult { Array = ..., Integer = ... };
}

您可以使用内置的类型基本上使得自定义类的定义简单一点:

You could use a built-in type that basically makes the definition of the custom class a bit easier:

private Tuple<int[], int> FunctionName(int[] inputArray)
{
    return Tuple.Create( ..., ... );
}

您可以使用退出参数:

private int[] FunctionName(int[] inputArray, out int integerResult)
{
    integerResult = 123;
    return new int[] { ... };
}

(显然,函数名和属性等,都只是例子......我相信你会挑选更有意义的名称)

(Obviously function names and properties, etc, are just examples... I assume you'll pick more meaningful names)

这篇关于C#函数返回两个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆