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