我读了这个问题的c++版本,但并没有真正理解它。

有人能解释清楚,如果它可以在c#中完成,以及如何?


当前回答

接受委托的方法可以向调用者提供多个值。这句话借鉴了我的答案,也引用了哈达斯公认的答案。

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.");
});

其他回答

要么返回类实例,要么使用out参数。这里有一个out参数的例子:

void mymethod(out int param1, out int param2)
{
    param1 = 10;
    param2 = 20;
}

这样叫它:

int i, j;
mymethod(out i, out j);
// i will be 20 and j will be 10

现在c# 7已经发布了,您可以使用新包含的元组语法

(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}.");

您还可以为元素提供名称(因此它们不是“Item1”、“Item2”等)。你可以通过在签名或返回方法中添加一个名字来实现:

(string first, string middle, string last) LookupName(long id) // tuple elements have names

or

return (first: first, middle: middle, last: last); // named tuple elements in a literal

它们也可以被解构,这是一个非常好的新功能:

(string first, string middle, string last) = LookupName(id1); // deconstructing declaration

查看这个链接,看看更多的例子可以做什么:)

你可以试试这个

public IEnumerable<string> Get()
 {
     return new string[] { "value1", "value2" };
 }

您还可以使用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;
}

你可以使用动态对象。我认为它比Tuple有更好的可读性。

static void Main(string[] args){
    var obj = GetMultipleValues();
    Console.WriteLine(obj.Id);
    Console.WriteLine(obj.Name);
}

private static dynamic GetMultipleValues() {
    dynamic temp = new System.Dynamic.ExpandoObject();
    temp.Id = 123;
    temp.Name = "Lorem Ipsum";
    return temp;
}