C# 函数返回多个值的方法

有时候我们需要一个函数返回多个值,网上更多是用out实现,我个人很喜欢用tuple方法。

tuple是一个元组,最多支持7个元素,再多需要嵌套等方法实现。

使用元组定义函数的方法如下:

public static Tuple<string,string> TupleFun() { string[] T = {‘hello‘,world}; Tuple<string, string> tup = new Tuple<string, string>(T[0], T[2]); return tup; }

元组还支持多种类型的值。

public static Tuple<string,int> TupleFun() { string T = ‘hello’; int q = 6; Tuple<string, int> tup = new Tuple<string, int>(T, q); return tup; }

在调用函数时,使用Item*来调用元组内的元素。

var tuple = TupleFun();print(tuple.Item1);print(int.Parse(tuple.Item2));

 

相关文章