Return multiple values to a method caller

前端 未结 26 2313
故里飘歌
故里飘歌 2020-11-21 21:57

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?

26条回答
  •  情歌与酒
    2020-11-21 22:52

    A method taking a delegate can provide multiple values to the caller. This borrows from my answer here and uses a little bit from Hadas's accepted answer.

    delegate void ValuesDelegate(int upVotes, int comments);
    void GetMultipleValues(ValuesDelegate callback)
    {
        callback(1, 2);
    }
    

    Callers provide a lambda (or a named function) and intellisense helps by copying the variable names from the delegate.

    GetMultipleValues((upVotes, comments) =>
    {
         Console.WriteLine($"This post has {upVotes} Up Votes and {comments} Comments.");
    });
    

提交回复
热议问题