[英]Having a C# method return more than one value of different data types?
我有一個函數,它有兩個參數:
string[], double[]
如何返回這兩個值? 怎么稱呼這個功能?
創建一個對象,其中包含要返回的值的屬性:
public class MyReturnType
{
public string[] MyStringArray { get; set; }
public double[] MyDoubleArray { get; set; }
}
然后,您的方法將返回此新類型:
public MyReturnType Foo()
{
...
return new MyReturnType { MyStringArray = strings; MyDoubleArray = doubles; };
}
嘿你可以使用關鍵字“out”:
column s1;
column s2;
public void method1(out value1, out value2)
{
select col1, col2, from tb1
value1 = col1;
value2 = col2;
}
使用Tuple結構(.NET 4.0中的新結構,但您可以根據它在自己的dll中創建一個 - 它是多個泛型類型的簡單容器)。
使用專門的運營商結構,如Michael Shimmins的回答說,但要使它成為一個結構,而不是一個類,除非它很大。
如果這是純粹的內部函數(案例問題),請使用dicitonary或對象數組。
使用參數。
你不能直接返回這個,但你可以使用strct返回它。 你可以為string和double創建struct並將值存儲在其中,之后你可以返回它。
你也可以使用ref操作符
您可以返回Hashtable
對象。 或者List
...或者您想要的任何類型的對象集合。
LE:
Hashtable process(string[] x, double[] y)
{
Hashtable output = new Hashtable();
// do whatever you want with x and y
output["stringArray"] = x;
output["doubleArray"] = y;
return output;
}
// ...
string[] stringArray = new string[] {};
double[] doubleArray = new double[] {};
// ...
Hashtable outcome = process(stringArray, doubleArray);
string[] data1 = (string[])outcome["stringArray"];
double[] data2 = (double[])outcome["doubleArray"];
// ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.