我正在尝试从字符串返回强类型的枚举值.我确信有更好的方法可以做到这一点.对于像这样的简单事情,这看起来像是太多的代码:
public static DeviceType DefaultDeviceType
{
get
{
var deviceTypeString = GetSetting("DefaultDeviceType");
if (deviceTypeString.Equals(DeviceType.IPhone.ToString()))
return DeviceType.IPhone;
if (deviceTypeString.Equals(DeviceType.Android.ToString()))
return DeviceType.Android;
if (deviceTypeString.Equals(DeviceType.BlackBerry.ToString()))
return DeviceType.BlackBerry;
if (deviceTypeString.Equals(DeviceType.Other.ToString()))
return DeviceType.Other;
return DeviceType.IPhone; // If no default is provided, use this default.
}
}
Run Code Online (Sandbox Code Playgroud)
想法?
根据我从社会得到了反馈,我决定使用一个字符串转换为一个枚举的方法扩展.它需要一个参数(默认枚举值).该默认还提供了类型,所以一般可以推断,不需要使用<>被明确指定.该方法现在缩短为:
public static DeviceType DefaultDeviceType
{
get
{
return GetSetting("DefaultDeviceType").ToEnum(DeviceType.IPhone);
}
}
Run Code Online (Sandbox Code Playgroud)
非常酷的解决方案,可以在将来重用.
LBu*_*kin 15
用途Enum.Parse():
var deviceTypeString = GetSetting("DefaultDeviceType");
return (DeviceType)Enum.Parse( typeof(DeviceType), deviceTypeString );
Run Code Online (Sandbox Code Playgroud)
如果输入不可靠,您应该注意,因为ArgumentException如果该值不能被解释为枚举的值之一,您将得到一个.
Parse()如果需要,还有一个重载允许您在进行此转换时忽略大小写.
kbr*_*ton 14
如果您正在处理(不可靠)用户输入,我喜欢使用允许默认值的扩展方法.试试看.
public static TResult ParseEnum<TResult>(this string value, TResult defaultValue)
{
try
{
return (TResult)Enum.Parse(typeof(TResult), value, true);
}
catch (ArgumentException)
{
return defaultValue;
}
}
Run Code Online (Sandbox Code Playgroud)