我读了这个问题的c++版本,但并没有真正理解它。
有人能解释清楚,如果它可以在c#中完成,以及如何?
我读了这个问题的c++版本,但并没有真正理解它。
有人能解释清楚,如果它可以在c#中完成,以及如何?
当前回答
你可以试试这个
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
其他回答
接受委托的方法可以向调用者提供多个值。这句话借鉴了我的答案,也引用了哈达斯公认的答案。
delegate void ValuesDelegate(int upVotes, int comments);
void GetMultipleValues(ValuesDelegate callback)
{
callback(1, 2);
}
调用方提供lambda(或命名函数),智能感知通过从委托复制变量名来帮助实现。
GetMultipleValues((upVotes, comments) =>
{
Console.WriteLine($"This post has {upVotes} Up Votes and {comments} Comments.");
});
不,在c#中(对于低于c# 7的版本),你不能从一个函数返回多个值,至少不能像在Python中那样。
然而,也有一些选择:
您可以返回一个object类型的数组,其中包含您想要的多个值。
private object[] DoSomething()
{
return new [] { 'value1', 'value2', 3 };
}
你可以使用out参数。
private string DoSomething(out string outparam1, out int outparam2)
{
outparam1 = 'value2';
outparam2 = 3;
return 'value1';
}
一些答案建议使用out参数,但我建议 不使用这个,因为它们不与异步方法一起工作。看到 这是更多的信息。
其他的答案是使用Tuple,我也会推荐它,但是使用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}.");
更多信息可以在这里找到。
你可以试试这个
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
你可以试试这个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);
输出:
输出:1,2