C#?函數(shù)返回多個值的方法詳情
引言
根據(jù) C# 語言規(guī)范,不可能從一個方法返回多個值。使用 C# 提供的一些其他功能,我們可以將多個值返回給調(diào)用者方法。本文概述了一些可用的替代方法來實現(xiàn)這一點。
1.使用ref參數(shù)
我們可以使用 ref
關鍵字 通過引用將值返回給調(diào)用者。我們可以使用它從一個方法中返回多個值,
如下所示:
using System; public class Example { private static void fun(ref int x, ref int y) { x = 1; y = 2; } public static void Main() { int x = 0; int y = 0; fun(ref x, ref y); Console.WriteLine("x = {0}, y = {1}", x, y); } } /* 輸出: x = 1, y = 2 */
請注意, ref
關鍵字不適用于 Async
和 Iterator
方法。
2.使用out參數(shù)修飾符
out
關鍵字導致參數(shù)通過引用傳遞。它就像 ref 關鍵字,除了 ref 要求在傳遞變量之前對其進行初始化。
下面的例子演示了使用 out 參數(shù)從方法返回多個值。
using System; public class Example { private static void fun(out int x, out int y) { x = 1; y = 2; } public static void Main() { int x = 0; int y = 0; fun(out x, out y); Console.WriteLine("x = {0}, y = {1}", x, y); } } /* 輸出: x = 1, y = 2 */
請注意, out 參數(shù)不適用于 Async 和 Iterator 方法。
3. 使用元組類
一個 tuple 是一種數(shù)據(jù)結(jié)構(gòu),可讓您輕松地將多個值打包到單個對象中。元組通常用于從方法返回多個值。
下面的示例創(chuàng)建一個 2 元組并從 fun() 方法:
using System; public class Example { private static Tuple<int, int> fun() { return Tuple.Create(1, 2); } public static void Main() { Tuple<int, int> tuple = fun(); Console.WriteLine("x = {0}, y = {1}", tuple.Item1, tuple.Item2); } } /* 輸出: x = 1, y = 2 */
tuple
是一個元組,最多支持7個元素,再多需要嵌套等方法實現(xiàn)。
使用元組定義函數(shù)的方法如下:
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; }
在調(diào)用函數(shù)時,使用Item*來調(diào)用元組內(nèi)的元素。
var tuple = TupleFun(); print(tuple.Item1); print(int.Parse(tuple.Item2));
4.使用C#7 ValueTuple
值元組,在 .NET Framework 4.7 中引入,是元組類型,用于在 C# 中提供元組的運行時實現(xiàn)。像元組類一樣,我們可以使用它以更有效的方式從方法中返回多個值。
下面的示例使用類型推斷來解構(gòu)該方法返回的 2 元組。
using System; public class Example { private static (int, int) fun() { return (1, 2); } public static void Main() { (int x, int y) = fun(); Console.WriteLine("x = {0}, y = {1}", x, y); } } /* 輸出: x = 1, y = 2 */
5. 使用結(jié)構(gòu)或類
在這里,想法是返回一個包含我們想要返回的所有字段的類的實例。以下代碼示例從使用 struct 的方法返回多個值。
using System; public class Example { private struct Pair { public int x; public int y; } private static Pair fun() { return new Pair { x = 1, y = 2 }; } public static void Main() { Pair pair = fun(); Console.WriteLine("x = {0}, y = {1}", pair.x, pair.y); } } /* 輸出: x = 1, y = 2 */
這就是從 C# 中的方法返回多個值的全部內(nèi)容。
到此這篇關于C# 函數(shù)返回多個值的方法詳情的文章就介紹到這了,更多相關C# 函數(shù)返回值內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
基于C#中IDisposable與IEnumerable、IEnumerator的應用
本篇文章小編為大家介紹,基于C#中IDisposable與IEnumerable、IEnumerator的應用,需要的朋友參考下2013-04-04c#打印預覽控件中實現(xiàn)用鼠標移動頁面功能代碼分享
項目中需要實現(xiàn)以下功能:打印預覽控件中,可以用鼠標拖動頁面,以查看超出顯示范圍之外的部分內(nèi)容,下面就是實現(xiàn)代碼2013-12-12