请问有没有更简单的方法基于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";
}
最佳答案
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;