簡體   English   中英

C#中的多個條件分配?

[英]Multiple conditional assignments in 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")

有一些簡潔的方法嗎? 你會怎么做?

使用開關

switch(temp)
{
    case 1:
        return "yes";
    case 2:
        return "no";
    case default:
        return "maybe";
}

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

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

var test = dictionairy[value];

該方法比switch語句更靈活,並且比嵌套的tenant運算符更易讀。

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");
  }
}

您可以使用switch語句

string temp = string.Empty;
switch(value)
{
    case 1:
        temp = "yes";
        break;
    case 2:
        temp = "no";
        break;
    case 3:
        temp = "maybe";
        break;
}

基本思想是:

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

實際實現它的方式有很多。 根據您的條件變量是什么,您可能希望將其實現為某種鍵值列表。 請參閱Zeebonk的答案作為示例。

最簡潔的答案是嵌套三元運算符

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

如果溫度值只有1,2,3

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

當然,這是所要求的簡潔答案,但這並不意味着它是最好的。 如果不能排除這種情況,將來您將需要更多的值進行測試,那么最好使用字典方法,如@zeebonk答案中所述。

此開關更接近您的偽代碼,並且是精確的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;
}

您的偽代碼不包含默認情況,但是包括一個默認情況。

顯而易見的答案是開關盒

但只是另一種味道:

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

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

您還可以扭轉局面:

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)將返回“否”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM