非通用版本(有效):
eTargets ParseTargets(string input)
{
eTargets targets = eTargets.None;
string[] items = input.Split(',');
foreach (var item in items)
{
eTargets target;
if (Enum.TryParse(item, out target))
{
targets |= target;
}
else
{
Logger.LogError("invalid target: " + item);
}
}
return targets;
}
尝试通用版本(不编译):
T ParseNames<T>(string delimitedNames) where T : struct
{
T result = default(T);
foreach (var name in delimitedNames.Split(','))
{
T parsed;
if (Enum.TryParse<T>(name, out parsed))
result |= (int)parsed; // ERROR: cannot convert T to int
// result |= parsed --> operator |= cannot be applied to T and int
}
return (T)result;
}
如果答案是“否”,理解潜在的限制将会有所帮助。
答案 0 :(得分:2)
怎么样
T ParseNames<T>(string delimitedNames) where T : struct //, Enum
{
return (T) Enum.Parse(typeof(T), delimitedNames);
}
您的代码已经隐含了1,2,4,8的编号,因此这里唯一的“差距”是[Flags]
属性的要求
答案 1 :(得分:1)
这应该有效:
static T ParseNames<T>(string delimitedNames) where T : struct
{
int result = 0;
foreach (var name in delimitedNames.Split(','))
{
result |= (int)Enum.Parse(typeof(T), name);
}
return (T)(object)result;
}