在 .NET 中使用“Type"和“Enum"作为参数 [英] Using 'Type' and 'Enum' as parameters in .NET
问题描述
我正在尝试编写一种将字符串参数解析为枚举的方法.枚举的类型也由参数决定.这是我的开始:
I'm trying to writing a method that parses a string parameter into an enum. The enum's type is also determined by a parameter. This is what I've started with:
public static type GetValueOrEmpty(string text, Type type)
{
if (!String.IsNullOrEmpty(text))
{
return (type)Enum.Parse(typeof(type)value);
}
else
{
// Do something else
}
}
显然,由于多种原因,这不起作用.有没有办法做到这一点?
Obviously this won't work for a number of reasons. Is there a way this can be done?
推荐答案
如果您在编译时知道类型,则可以改为使用泛型:
You can make it generic instead, if you know the type at compile-time:
public static T GetValueOrEmpty<T>(string text)
{
if (!String.IsNullOrEmpty(text))
{
return (T) Enum.Parse(typeof(T), text);
}
else
{
// Do something else
}
}
如果您在编译时不知道类型,那么让方法返回该类型对您来说没有多大用处.你当然可以让它返回object
:
If you don't know the type at compile-time, then having the method return that type won't be much use to you. You can make it return object
of course:
public static object GetValueOrEmpty(string text, Type type)
{
if (!String.IsNullOrEmpty(text))
{
return Enum.Parse(type, text);
}
else
{
// Do something else
}
}
如果这些都对您没有用,请提供有关您要实现的目标的更多信息.
If neither of these are useful to you, please give more information about what you're trying to achieve.
这篇关于在 .NET 中使用“Type"和“Enum"作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!