C#函数返回多个值

2020/11 11 10:11
方法一:使用结构体包一下
struct MultiObj
{
  int a;
  int b;
  string c;
}

MultiObj getVal();


方法二:使用out关键字逐个传出
void getVal(out int a, out int b, out string c);


方法三:使用元组Tuple(C#4.0以上)
Tuple<int, int, string> getVal()
{
    return Tuple.Create(100, 100, "what");
    return new Tuple<int, int, string>(100, 100, "what");
}

var k = getVal();
var c = k.Item1 + k.Item2;


方法四:使用元组语法糖(C#7.0以上)
(int, int, string) getVal()
{
  return (100, 100, "what");
}

var k = getVal();
var c = k.Item1 + k.Item2;

-----------------------------------------------------

(int, int, string) obj1 = (100, 100, "what1");
(int, int, string) obj2 = (100, 100, "what2");
if (obj1 == obj2) ...

--转载请注明: http://blog.coolcoding.cn/?p=2858