How can I return multiple values from a function i

2018-12-31 04:42发布

I read the C++ version of this question but didn't really understand it.

Can someone please explain clearly if it can be done and how?

25条回答
只靠听说
2楼-- · 2018-12-31 05:04

No, you can't return multiple values from a function in C# (for versions lower than C# 7), at least not in the way you can do it in Python.

However, there are a couple alternatives:

You can return an array of type object with the multiple values you want in it.

private object[] DoSomething()
{
    return new [] { 'value1', 'value2', 3 };
}

You can use out parameters.

private string DoSomething(out string outparam1, out int outparam2)
{
    outparam1 = 'value2';
    outparam2 = 3;
    return 'value1';
}
查看更多
零度萤火
3楼-- · 2018-12-31 05:04

you can try this "KeyValuePair"

private KeyValuePair<int, int> GetNumbers()
{
  return new KeyValuePair<int, int>(1, 2);
}


var numbers = GetNumbers();

Console.WriteLine("Output : {0}, {1}",numbers.Key, numbers.Value);

Output :

Output : 1, 2

查看更多
孤独寂梦人
4楼-- · 2018-12-31 05:07

Future version of C# is going to include named tuples. Have a look at this channel9 session for the demo https://channel9.msdn.com/Events/Build/2016/B889

Skip to 13:00 for the tuple stuff. This will allow stuff like:

(int sum, int count) Tally(IEnumerable<int> list)
{
// calculate stuff here
return (0,0)
}

int resultsum = Tally(numbers).sum

(incomplete example from video)

查看更多
栀子花@的思念
5楼-- · 2018-12-31 05:09

If you mean returning multiple values, you can either return a class/struct containing the values you want to return, or use the "out" keyword on your parameters, like so:

public void Foo(int input, out int output1, out string output2, out string errors) {
    // set out parameters inside function
}
查看更多
君临天下
6楼-- · 2018-12-31 05:11

You can also use an OperationResult

public OperationResult DoesSomething(int number1, int number2)
{
// Your Code
var returnValue1 = "return Value 1";
var returnValue2 = "return Value 2";

var operationResult = new OperationResult(returnValue1, returnValue2);
return operationResult;
}
查看更多
明月照影归
7楼-- · 2018-12-31 05:12

Some of these answers stated that use out parameter but I recommend not using this due to they don’t work with async methods. See this for more information.

Other answers stated using Tuple, which I would recommend too but using the new feature introduced in C# 7.0.

(string, string, string) LookupName(long id) // tuple return type
{
    ... // retrieve first, middle and last from data storage
    return (first, middle, last); // tuple literal
}

var names = LookupName(id);
WriteLine($"found {names.Item1} {names.Item3}.");

Further information can be found here.

查看更多
登录 后发表回答