HasFlag with a generic enum?

≯℡__Kan透↙ 提交于 2019-12-08 18:46:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!