简体   繁体   中英

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

Some types has the TryParse method, for example it is Int32 , Int64 , Boolean , etc. It allows check the string value without try\\catch block. It very much influences on productivity when many incorrect values are processing in a cycle. I need to do the same for string value of the LCID. But the CultureInfo class has not the TryParse method.

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

How can I rewrite this code?

You could cache all the CultureInfo objects by LCID in a dictionary:

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

and use TryGetValue like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM