简体   繁体   中英

How to create extension method on enumeration (c#)

I want to create an extension method that will return an enum value by its key. The usage will be

LifeCycle.GetLifeCycle(1) 

or LifeCycle.GetLifeCycleByValue("")

Here is what I thought of - Let's say I have the following enum :

public enum LifeCycle
{
    Pending = 0,
    Approved = 1,
    Rejected = 2,
}

And I wrote the following extension for the getByint case

public static class EnumerationExtensions
{
    private static Dictionary<int, LifeCycle> _lifeCycleMap = Enum.GetValues(typeof(LifeCycle)).Cast<int>().ToDictionary(Key => Key, value => ((LifeCycle)value));

    public static LifeCycle GetLifeCycle(this LifeCycle lifeCycle, int lifeCycleKey)
    {
        return _lifeCycleMap[lifeCycleKey];
    }
}

So far

 LifeCycle.GetLifeCycle(1) 

doenst compile.

Is that even possible ?

There is no such thing as a static extension method, which is what you're trying to do. You can only create extension methods that act in instances of a type, not the type itself.

LifeCycle is the type not an instance of that enum.

So this would compile:

LifeCycle.Pending.GetLifeCycle(1);

But this extension is pointless anyway since you could get an enum by it's int value directly:

LifeCycle approved = (LifeCycle) 1;

You just need cast like this:

var lifeCycle = (LifeCycle)1;

Here go some example:

using System;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            var lifeCycle = (LifeCycle)1;
            Console.WriteLine(lifeCycle);
            //Output: Approved
        }
    }

    public enum LifeCycle
    {
        Pending = 0,
        Approved = 1,
        Rejected = 2,
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM