C#中的多个条件赋值?

pro*_*don 1 c#

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

伪码

int temp = (either 1, 2, or 3)
string test = (if temp = 1, then "yes") (if temp = 2, then "no") (if temp = 3, then "maybe")
Run Code Online (Sandbox Code Playgroud)

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

Err*_*Efe 11

使用开关

switch(temp)
{
    case 1:
        return "yes";
    case 2:
        return "no";
    case default:
        return "maybe";
}
Run Code Online (Sandbox Code Playgroud)


zee*_*onk 5

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

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

var test = dictionairy[value];
Run Code Online (Sandbox Code Playgroud)

此方法比switch语句更灵活,并且比嵌套的tenary运算符语句更具可读性.