用一个通用的枚举HasFlag? [英] HasFlag with a generic enum?
问题描述
我刚开始用泛型
在C#中,但已早早就遇到一个问题,我怎么能叫 .HasFlag()
上一个通用的枚举
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 {
}
我如何添加 [国旗]
属性呢?
推荐答案
调用实例方法将需要拳无论如何,所以,因为你不能限制在枚举
,只是放弃仿制药,并使用枚举
。例如,而不是:
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 ...
}
做到这一点:
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;
这篇关于用一个通用的枚举HasFlag?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!