简体   繁体   English

如何在C#中实现多个返回值,如python样式

[英]How to achieve multiple return values in C# like python style

I have a python script: 我有一个python脚本:

def f():
    a = None
    b = None
    return (a, b)


a, b = f()

It's so easy to achieve multiple return values in python. 在python中实现多个返回值非常容易。 And now I want to achieve the same result in C#. 现在我想在C#中实现相同的结果。 I tried several ways, like return int[] or KeyValuePair. 我试过几种方法,比如return int []或KeyValuePair。 But both ways looked not elegant. 但两种方式看起来并不优雅。 I wonder a exciting solution. 我想知道一个令人兴奋的解 thanks a lot. 非常感谢。

Use Tuple class. 使用元组类。

  public Tuple<int,int> f()
  {
        Tuple<int,int> myTuple = new Tuple<int,int>(5,5);
        return myTuple;
  }

Unfortunately, C# does not support this. 不幸的是,C#不支持这一点。 The closest you can get is to use out parameters: 你可以得到的最接近的是使用out参数:

void f(out int a, out int b) {
    a = 42;
    b = 9;
}

int a, b;
f(out a, out b);

You can obviously do 你显然可以这样做

object F(out object b)
{
    b = null;
    return null
}

object b;
var a = F(out b)

but better to use Tuple with a functional style, 但最好使用具有功能风格的Tuple

Tuple<object, object> F()
{
    return Tuple.Create<object, object>(null, null);
}

var r = F();
var a = r.Item1;
var b = r.Item2;

but, since in c# you can be explicit, why not define your return type. 但是,因为在c#中你可以是明确的,为什么不定义你的返回类型。

struct FResult
{
    public object A;
    public object B;
}

FResult F()
{
    return new FResult();
}

var r = F();
var a = F.A;
var b = F.B;

This seems like a small price to pay for the semantic benefits. 这似乎是为语义效益付出的小代价。

This feature is available in C#7 with .Net 4.7. 此功能在C#7中以.Net 4.7提供。

private (string a, string b) f()
{
    return (a: null, b: null);
    // or simply: return (null, null);
}

var (a, b) = f();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM