Help creating an Enum extension helper

Take this listing, for example:

public enum PersonName : short
{
    Mike = 1,
    Robert= 2
}

I want to use the extension method as follows:

PersonName person = PersonName.Robert;
short personId = person.GetId();
//Instead of:
short personId = (short)person;

Any idea how to implement this?

it should be common to int, short, etc., as well as to general enumerations, and not just to PersonName.

+3
source share
5 answers

It's impossible.

You cannot restrict a method based on a base type enum.

Explanation:

Here's how you can do it:

public static TNumber GetId<TEnum, TNumber>(this TEnum val) 
       where TEnum : Enum 
       where TEnum based on TNumber

Unfortunately, the first restriction is not allowed by C # , and the second restriction is not supported by the CLR.

+2
source

Well, it’s possible, but on the other hand you will need to specify what the base type is:

public static T GetId<T>(this Enum value) 
                        where T : struct, IComparable, IFormattable, IConvertible
{
    return (T)Convert.ChangeType(value, typeof(T));
}

System.Enum . :

PersonName person = PersonName.Robert;
short personId = person.GetId<short>();

- long, :

public static long GetId(this Enum value)
{
    return Convert.ToInt64(value);
}

:

PersonName person = PersonName.Robert;
long personId = person.GetId();

object, :

public static object GetId(this Enum value)
{
    return Convert.ChangeType(task, Enum.GetUnderlyingType(value.GetType()));
}

PersonName person = PersonName.Robert;
var personId = (short)person.GetId(); 
// but that sort of defeats the purpose isnt it?

- . ( int, ), .

+2

, PersonName:

public static class PersonExtensions // now that sounds weird...
{
    public static short GetID (this PersonName name)
    {
        return (short) name;
    }
}

node: - , , :)

0

, ? , .

0
source

I would just use something like IEnumerable<KeyValuePair<string,short>>or Dictionary<string,short>... you can add your extensions to an IDictionary or IEnumerable if you want.

0
source

Source: https://habr.com/ru/post/1733438/


All Articles