Non Generic Version (works):
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;
}
Attempt at generic version (does not compile):
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;
}
如果答案是“否”,那么理解基本限制将是有益的。