.net 是否有在创建 RegionInfo 对象之前验证区域名称的内置方法?
Does .net have an inbuilt way of validating region names before creating a RegionInfo object?
我的代码如下所示:
var twoLetterCountryCode = *Get possibly invalid value from database*;
if (!string.IsNullOrEmpty(twoLetterCountryCode) && twoLetterCountryCode.Length == 2)
{
try
{
var region = new RegionInfo(twoLetterCountryCode);
}
catch (ArgumentException ex)
{
*log exception*
}
}
是否有一种内置的方法来验证区域名称,这样我就不必使用 try/catch?
没有,没有RegionInfo.TryParse
,不知道他们为什么不提供。他们有信息,但所有内容都是 internal
,因此您无法访问它。
所以在我看来 try-catch
没问题。你可以把它放在扩展方法中。
public static class StringExtensions
{
public static bool TryParseRegionInfo(this string input, out RegionInfo regionInfo)
{
regionInfo = null;
if(string.IsNullOrEmpty(input))
return false;
try
{
regionInfo = new RegionInfo(input);
return true;
}
catch (ArgumentException)
{
return false;
}
}
}
我的代码如下所示:
var twoLetterCountryCode = *Get possibly invalid value from database*;
if (!string.IsNullOrEmpty(twoLetterCountryCode) && twoLetterCountryCode.Length == 2)
{
try
{
var region = new RegionInfo(twoLetterCountryCode);
}
catch (ArgumentException ex)
{
*log exception*
}
}
是否有一种内置的方法来验证区域名称,这样我就不必使用 try/catch?
没有,没有RegionInfo.TryParse
,不知道他们为什么不提供。他们有信息,但所有内容都是 internal
,因此您无法访问它。
所以在我看来 try-catch
没问题。你可以把它放在扩展方法中。
public static class StringExtensions
{
public static bool TryParseRegionInfo(this string input, out RegionInfo regionInfo)
{
regionInfo = null;
if(string.IsNullOrEmpty(input))
return false;
try
{
regionInfo = new RegionInfo(input);
return true;
}
catch (ArgumentException)
{
return false;
}
}
}