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

查看:48
本文介绍了在 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,最好使用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天全站免登陆