gpt4 book ai didi

c# - 处理以下代码的更好方法

转载 作者:太空宇宙 更新时间:2023-11-03 18:12:52 24 4
gpt4 key购买 nike

private bool CheckMemberCountry(string country)
{
string[] countries = new string[] { "AF", "BD", "CA", "IN", "IR", "RO", "AN", "CY", "IL", "PH" };
foreach (string memberCountry in countries)
{
if (memberCountry.Equals(country))
{
return true;
}
}

return false;
}

我不想硬编码上面的值,我该如何处理

最佳答案

最短的方法是将其重写为一行,但这不是最有效的:

return (new string[] { "AF", "BD", "CA", "IN", "IR", "RO", "AN", "CY", "IL", "PH" })
.Contains(country);

您应该将数组设为静态只读变量,并在您的函数中使用它:

private static readonly string[] AllCountries = new string[] {
"AF", "BD", "CA", "IN", "IR", "RO", "AN", "CY", "IL", "PH"
};

private bool CheckMemberCountry(string country) {
return AllCountries.Contains(country);
}

关于c# - 处理以下代码的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11469376/

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