1

好的,如果我有一个字符串,我希望基于多个条件等于某个字符串,那么实现它的最佳方法是什么?

伪代码

int temp = (either 1, 2, or 3)
string test = (if temp = 1, then "yes") (if temp = 2, then "no") (if temp = 3, then "maybe")

有没有一些简洁的方法来做到这一点?你会怎么办?

4

9 回答 9

11

使用开关

switch(temp)
{
    case 1:
        return "yes";
    case 2:
        return "no";
    case default:
        return "maybe";
}
于 2012-09-21T20:27:42.730 回答
5

您可以使用其他答案中提到的 switch 语句,但也可以使用字典:

var dictionary = new Dictionary<int, string>();
dictionary.Add(1, "yes");
dictionary.Add(2, "no");
dictionary.Add(3, "maybe");

var test = dictionairy[value];

这种方法比 switch 语句更灵活,并且比嵌套的三元运算符语句更具可读性。

于 2012-09-21T20:31:40.390 回答
4
string test = GetValue(temp);

public string GetValue(int temp)
{
  switch(temp)
  {
    case 1:
      return "yes";

    case 2:
      return "no";

    case 3:
      return "maybe";

    default:
      throw new ArgumentException("An unrecognized temp value was encountered", "temp");
  }
}
于 2012-09-21T20:30:00.970 回答
2

你可以使用一个switch语句

string temp = string.Empty;
switch(value)
{
    case 1:
        temp = "yes";
        break;
    case 2:
        temp = "no";
        break;
    case 3:
        temp = "maybe";
        break;
}
于 2012-09-21T20:27:34.157 回答
2

基本思想是:

String choices[] = {"yes","no","maybe"};
string test = choices[temp-1];

有许多不同的方法来实际实现它。根据您的条件变量是什么,您可能希望将其实现为某种键值列表。例如,请参阅 Zeebonk 的答案。

于 2012-09-21T20:31:33.373 回答
1

最简洁的答案是嵌套三元运算符

string test = (temp == 1 ? "yes" : (temp == 2 ? "no" : (temp == 3 ? "maybe" : "")));

如果温度值只有 1,2,3 那么

string test = (temp == 1 ? "yes" : (temp == 2 ? "no" : "maybe"));

当然,这是所要求的简洁答案,但这并不意味着它是最好的。如果您不能排除这一点,那么将来您将需要更多的值来测试,那么最好使用@zeebonk 答案中解释的字典方法。

于 2012-09-21T20:29:13.390 回答
1

此开关更接近您的伪代码,并且是精确的 C# 代码:

int temp = /* 1, 2, or 3 */;
string test;
switch(temp)
{
    case 1:
        test = "yes";
        break;
    case 2:
        test = "no";
        break;
    case 3:
        test = "maybe";
        break;
    default:
        test = /* whatever you want as your default, if anything */;
        break;
}

您的伪代码不包含默认情况,但最好包含默认情况。

于 2012-09-21T20:42:19.560 回答
0

显而易见的答案是开关盒

但只是另一种味道:

int temp = x; //either 1,2 or 3

string test = (temp == 1 ? "yes" : temp == 2 ? "no" : "maybe");
于 2012-09-21T20:30:21.340 回答
0

你也可以扭转局面:

class Program
{
    enum MyEnum
    {
        Yes = 1, 
        No, 
        Maybe
    }

    static void Main(string[] args)
    {
        Console.WriteLine(MyEnum.Maybe.ToString());
        Console.ReadLine();
    }
}

这也更符合 temp 只能是 1、2 或 3。如果它是 int 编译器,如果 temp 的值为 34,编译器不会警告您。

你也可以这样做:

string GetText(int temp){ 
    return ((MyEnum)temp).ToString();
}

GetText(2) 将返回“否”

于 2012-09-21T21:31:15.110 回答