在C#中使用函数返回两个字符串 [英] Return two strings with a function in C#

查看:93
本文介绍了在C#中使用函数返回两个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要返回两个值的函数.这可能吗?

I have a function where I want to return two values. Is this possible?

这是我的代码,但似乎不希望我返回两个值:

This is my code, but it doesn't seem to like that I want to return two values:

public string PlayerCards(string player1C1, string player1C2)
{
    generatedCard = randomCard.Next(1, 52);
    player1C1 = generatedCard.ToString();
    player1C1 = player1C1 + ".png";
    return player1C1, player1C2;
}

推荐答案

某些选项:

  • 使用 out 参数:

public string PlayerCards(out string x)

返回一个值,并将 out 参数(在这种情况下为 x )设置为另一个值;调用代码还需要指定一个带有 out 的参数,并且在调用完成后,调用者将能够看到方法中设置的值.

Return one value, and set the out parameter (x in this case) to another value; the calling code will need to specify an argument with out as well, and after the call has completed, the caller will be able to see the value set in the method.

(尚不清楚您为什么完全接受参数;您似乎并没有真正使用它们.)

(It's not clear why you're accepting parameters at all; you don't seem to really use them.)

返回一个 ValueTuple< string,string> ,最好使用C#7元组提供元素名称

Return a ValueTuple<string, string>, ideally using C# 7 tuples to provide element names

根本不清楚您的代码试图执行的操作-方法的名称不清楚,并且您不使用参数.当您弄清楚了该方法要达到的目的-对您自己以及对我们一样-答案很可能会变得更加明显.

It's not at all clear what your code is trying to do - the name of the method isn't clear and you don't use the parameters. When you've clarified what the method is trying to achieve - to yourself as much as to us - the answer may well become more obvious.

我也鼓励您在适当的地方使用局部变量-我怀疑 generatedCard 应该是局部变量,而不是当前的(大概)实例变量.

I'd also encourage you to use local variables where appropriate - I suspect generatedCard should be a local variable instead of the (presumably) instance variable it currently is.

这篇关于在C#中使用函数返回两个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆