How to return multiple values in C# 7? [closed]

℡╲_俬逩灬. 提交于 2019-11-30 12:23:46

问题


A team mate told me that in C# 7.0 it's is possibile to return multiple values from a function natively. Can anybody provide some example? Thanks


回答1:


What do you mean by natively?

Actualy C# 7 has a very useful new feature that lets you return more than one value from a method thanks to tuple types and tuple literals.

Consider the following function:

(string, string, string) MyCoolFunction() // tuple return type
{   
    //...        
    return (firstValue, secondValue, thirdValue);
}

Which can be used like this:

var values = MyCoolFunction();
var firstValue = values.Item1;
var secondValue = values.Item2;
var thirdValue = values.Item3;

Or by using deconstruction syntax

(string first, string second, string third) = MyCoolFunction();

//...

var (first, second, third) = MyCoolFunction(); //Implicitly Typed Variables

Take some time to check out the Documentation, they have some very good examples (this answer's one are based on them!).




回答2:


You are looking for Tuples. This is an example:

static (int count, double sum) Tally(IEnumerable<double> values)
{
    int count = 0;
    double sum = 0.0;
    foreach (var value in values)
    {
        count++;
        sum += value;
    }
    return (count, sum);
}

...

var values = ...
var t = Tally(values);
Console.WriteLine($"There are {t.count} values and their sum is {t.sum}");

Example stolen from http://www.thomaslevesque.com/2016/07/25/tuples-in-c-7/




回答3:


You can also implement like this:

public class Program
{
    public static void Main(string[] args)
    {

        var values=GetNumbers(6,2);
        Console.Write(values);


    }

    static KeyValuePair<int,int> GetNumbers(int x,int y)
    {
        return new KeyValuePair<int,int>(x,y);
    }
}


来源:https://stackoverflow.com/questions/42926301/how-to-return-multiple-values-in-c-sharp-7

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!