gpt4 book ai didi

c# - 返回基于 int 的字符串

转载 作者:太空宇宙 更新时间:2023-11-03 17:54:13 25 4
gpt4 key购买 nike

在 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;

关于c# - 返回基于 int 的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16078805/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com