我正在尝试编写一个将字符串参数解析为枚举的方法.枚举的类型也由参数决定.这是我开始的:
public static type GetValueOrEmpty(string text, Type type)
{
if (!String.IsNullOrEmpty(text))
{
return (type)Enum.Parse(typeof(type)value);
}
else
{
// Do something else
}
}
Run Code Online (Sandbox Code Playgroud)
显然,由于多种原因,这不起作用.有没有办法可以做到这一点?
Jon*_*eet 14
如果你在编译时知道类型,你可以改为通用:
public static T GetValueOrEmpty<T>(string text)
{
if (!String.IsNullOrEmpty(text))
{
return (T) Enum.Parse(typeof(T), text);
}
else
{
// Do something else
}
}
Run Code Online (Sandbox Code Playgroud)
如果您在编译时不知道类型,那么让方法返回该类型将对您没有多大用处.你可以让它返回object当然:
public static object GetValueOrEmpty(string text, Type type)
{
if (!String.IsNullOrEmpty(text))
{
return Enum.Parse(type, text);
}
else
{
// Do something else
}
}
Run Code Online (Sandbox Code Playgroud)
如果这些都不适合您,请提供有关您要实现的目标的更多信息.