开发者

Is there a way to make ToEnum generic

开发者 https://www.devze.com 2022-12-24 00:10 出处:网络
I would like to do th开发者_StackOverflowis but it does not work. bool TryGetEnum<TEnum, TValue>(TValue value, out TEnum myEnum)

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

精彩评论

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