1

有没有一种更简单的方法可以根据 C# .NET2 中的 int 值返回一个字符串?

        if (intRelatedItems == 4)
        {
            _relatedCategoryWidth = "3";
        }
        else if (intRelatedItems == 3)
        {
            _relatedCategoryWidth = "4";
        }
        else if (intRelatedItems == 2)
        {
            _relatedCategoryWidth = "6";
        }
        else if (intRelatedItems == 1)
        {
            _relatedCategoryWidth = "12";
        }
        else
        {
            _relatedCategoryWidth = "0";
        }
4

5 回答 5

7
Dictionary<int, string> dictionary = new Dictionary<int, string>
{
    {4, "3"},
    {3, "4"},
    {2, "6"},
    {1, "12"},
};

string defaultValue = "0";

if(dictionary.ContainsKey(intRelatedItems))
    _relatedCategoryWidth = dictionary[intRelatedItems];
else
    _relatedCategoryWidth = defaultValue;

或使用三元运算符,但我发现它的可读性较差:

_relatedCategoryWidth = dictionary.ContainsKey(intRelatedItems) ? dictionary[intRelatedItems] : defaultValue;

或使用TryGetValue方法,如 CodesInChaos 建议:

if(!dictionary.TryGetValue(intRelatedItems, out _relatedCategoryWidth))
    _relatedCategoryWidth = defaultValue;
于 2013-04-18T09:12:12.647 回答
1

您可以使用条件运算符:

_relatedCategoryWidth =
  intRelatedItems == 4 ? "3" :
  intRelatedItems == 3 ? "4" :
  intRelatedItems == 2 ? "6" :
  intRelatedItems == 1 ? "12" :
  "0";

这种写法强调一切都归结为对_relatedCategoryWidth变量的赋值。

于 2013-04-18T09:25:41.367 回答
1

好吧,既然你只对特殊情况下的连续小整数感兴趣,你可以通过数组查找来做到这一点:

var values = new[] { "0", "12", "6", "4", "3" };
if (intRelatedItems >= 0 && intRelatedItems < values.Length)
{
    return values[intRelatedItems];
}
else
{
    return "0";
}

否则,最好的选择是使用普通的旧switch/case并可能将其隐藏在方法中,以免混淆代码。

于 2013-04-18T09:13:23.747 回答
0

您可以使用int[]or Dictionary<int, string>,具体取决于您的键。

例如:

int[] values = new int[] {100, 20, 10, 5};
return values[intRelatedItems];

显然,只有在intRelatedItems只能将值从 0 到 values.Length -1 时才有效。

如果不是这种情况,您可以使用“字典”。如果未找到密钥,两种解决方案都可能引发异常。

于 2013-04-18T09:13:24.230 回答
0
Dictionary<int, string> dictLookUp = new Dictionary<int, string>();
dictLookUp.Add(4, "3");
dictLookUp.Add(3, "4"};
dictLookUp.Add(2, "6"};
dictLookUp.Add(1, "12"};

int defaultVal = 0;

if (dictLookUp.ContainsKey(intRelatedItems))
{
    relatedCategoryWidth  = dictLookUp[intRelatedItems];
}
else
{ 
    intRelatedItems = defaultVal;
}
于 2013-04-18T09:17:51.020 回答