1.c#返回多个不同类型值的方式
使用ref,out,元组,对象
2.元组的使用
当然上面的方式中ref和out我们从第一印象来说,ref和out更多看作指针来使用,对象的声明太麻烦,因此活用起来,元组更加直白和简洁。当然元组也和数组一样继承底层比较接口,具体看官方文档,下面是使用元组返回多个值的方式
class Program { static void Main(string[] args) { var value = GetTowValue(); Console.WriteLine("输出元组1:"+value.a + "," + value.b); var value2 = GetMore(); Console.WriteLine("输出元组2:"+value2.a1 + "," + value2.a2 + "," + value2.a3 + "," + value2.a4 + "," + value2.a5 + "," + value2.a6 + "," + value2.a7); var value3 = Divide(10, 3); Console.WriteLine("输出元组3:" + value3.Item1 + "," + value3.Item2); } //输出两个数据的元组 private static (int a,string b) GetTowValue() { int i1 = 1; string i2 = "2"; return (i1, i2); } //更多数据的元组 private static (int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10, int a11) GetMore() { return (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); } //使用关键字 public static Tuple<int,int> Divide(int dividend,int divisor) { int result = dividend / divisor; int remainder = dividend % divisor; return Tuple.Create(result, remainder); } }
输出