开发者

Is there a way to make ToEnum generic

I would like to do th开发者_StackOverflowis but it does not work.

bool TryGetEnum<TEnum, TValue>(TValue value, out TEnum myEnum)
{

    value = default(TEnum);
    if (Enum.IsDefined(typeof(TEnum), value))
    {
        myEnum = (TEnum)value;
        return true;
    }
    return false;
}

Example usage:

MyEnum mye;
bool success = this.TryGetEnum<MyEnum,char>('c',out mye);


Try the following

myEnum = (TEnum)((object)value);


The best you will be able to do is this:

bool TryGetEnum<TEnum>(Object value, out TEnum myEnum)
{
    myEnum = default(TEnum);
    if (Enum.IsDefined(typeof(TEnum), value))
    {
        myEnum = (TEnum)value;
        return true;
    }
    return false;
}

With a use case that looks something like this:

MyEnum mye;
bool success = this.TryGetEnum<MyEnum>(2, out mye);

You won't be able to make the input type generic as there are no generic constraints available for you to leverage that would enable you to guarantee that TEnum uses TValue as its underlying type.

Also, (as a side note) C# only allows the following types to be used as the underlying value for an enum:

  • byte
  • sbyte
  • short
  • ushort
  • int
  • uint
  • long
  • ulong
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜