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[1]);
            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));

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM