问题
I am just starting with Generics
in C# but have run into a problem early on, how can I call .HasFlag()
on a generic Enum
?
public class Example<TEnum> where TEnum : struct {
}
How can I add the [Flags]
attribute to it?
回答1:
Calling the instance method will require boxing anyway, so, since you can't constrain to Enum
, just abandon generics and use Enum
. For example, instead of:
void Something(TEnum enumValue, TEnum flags)
{
if (enumValue.HasFlags(flags))
//do something ...
}
Do this:
void Something(Enum enumValue, Enum flags)
{
if (enumValue.HasFlags(flags))
//do something ...
}
In a generic method, you could achieve your goal like this:
void Something(TEnum enumValue, TEnum flags)
{
Enum castValue = (Enum)(object)enumValue;
Enum castFlags = (Enum)(object)flags;
if (castValue.HasFlags(castFlags))
//do something ...
}
This will throw an exception at runtime if you call the method with a value type that isn't an enum. You could also cast via ValueType
rather than object
, since the type parameter is known to represent a value type:
Enum castValue = (Enum)(ValueType)enumValue;
来源:https://stackoverflow.com/questions/9519596/hasflag-with-a-generic-enum