如何在没有 try\catch 块的情况下检查 LCID 的有效性?

How can I check the validation of the LCID without try\catch block?

有些类型有TryParse方法,例如Int32Int64Boolean等。它允许在没有[=22的情况下检查字符串值=] 块。当在一个循环中处理许多不正确的值时,它会极大地影响生产率。我需要对 LCID 的字符串值执行相同的操作。但是 CultureInfo class 没有 TryParse 方法。

CultureInfo culture = null;
try {
  culture = CultureInfo.GetCultureInfo(Convert.ToInt32(lcid, 16));
}
catch {
}

如何重写这段代码?

您可以在字典中按 LCID 缓存所有 CultureInfo 对象:

var culturesByLcid = CultureInfo
    .GetCultures(CultureTypes.AllCultures)
    .ToDictionary(c => c.LCID, c => c);

并像这样使用 TryGetValue:

CultureInfo found;
if (culturesByLcid.TryGetValue(lcid, out found))
{
    ...
}