Dav*_*.ca 16 .net c# generics enums
我有一个像这样的枚举类型作为例子:
public Enum MyEnum {
enum1, enum2, enum3 };
Run Code Online (Sandbox Code Playgroud)
我将从配置文件中读取一个字符串.我需要它来解析字符串到MyEnum类型或null o未定义.不确定以下代码是否有效(对不起现在无法访问我的VS):
// example: ParseEnum<MyEnum>("ENUM1", ref eVal);
bool ParseEnum<T>(string value1, ref eVal) where T : Enum
{
bool bRet = false;
var x = from x in Enum.GetNames(typeof(T)) where
string.Equals(value1, x, StringComparison. OrdinalIgnoreCase)
select x;
if (x.Count() == 1 )
{
eVal = Enum.Parse(typeof(T), x.Item(0)) as T;
bRet = true;
}
return bRet;
}
Run Code Online (Sandbox Code Playgroud)
不确定它是否正确或有任何其他简单的方法将字符串解析为MyEnum值?
Rex*_*x M 31
怎么样的:
public static class EnumUtils
{
public static Nullable<T> Parse<T>(string input) where T : struct
{
//since we cant do a generic type constraint
if (!typeof(T).IsEnum)
{
throw new ArgumentException("Generic Type 'T' must be an Enum");
}
if (!string.IsNullOrEmpty(input))
{
if (Enum.GetNames(typeof(T)).Any(
e => e.Trim().ToUpperInvariant() == input.Trim().ToUpperInvariant()))
{
return (T)Enum.Parse(typeof(T), input, true);
}
}
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
用作:
MyEnum? value = EnumUtils.Parse<MyEnum>("foo");
Run Code Online (Sandbox Code Playgroud)
(注:旧版本try/catch
左右使用Enum.Parse
)
private enum MyEnum
{
Enum1 = 1, Enum2 = 2, Enum3 = 3, Enum4 = 4, Enum5 = 5, Enum6 = 6,
Enum7 = 7, Enum8 = 8, Enum9 = 9, Enum10 = 10
}
private static Object ParseEnum<T>(string s)
{
try
{
var o = Enum.Parse(typeof (T), s);
return (T)o;
}
catch(ArgumentException)
{
return null;
}
}
static void Main(string[] args)
{
Console.WriteLine(ParseEnum<MyEnum>("Enum11"));
Console.WriteLine(ParseEnum<MyEnum>("Enum1"));
Console.WriteLine(ParseEnum<MyEnum>("Enum6").GetType());
Console.WriteLine(ParseEnum<MyEnum>("Enum10"));
}
Run Code Online (Sandbox Code Playgroud)
OUTPUT:
//This line is empty as Enum11 is not there and function returns a null
Enum1
TestApp.Program+MyEnum
Enum10
Press any key to continue . . .
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
35821 次 |
最近记录: |