简体   繁体   中英

Methods in c# enums

In Java we can use methods in enums, for example i can write

 public static void main(String []args){
    System.out.println(GetNum.TWO.get());
 }

 enum GetNum{
     ONE{
         public int get(){
             return 1;
         }
     },
     TWO{
         public int get(){
             return 2;
         }
     };
     public abstract int get();
 }

maybe somebody can say me: in c# enums can I do something like this?

Not really, but you can sort of though the use of extension methods.

Given an enumeration such as

enum HurfDurf
{
    Hurr,
    Durr
}

you can create an extension method such as

static class HurfDurfExtensions
{
    public static string Wat(this HurfDurf lol)
    {
        return lol == HurfDurf.Hurr ? "Wew lad" : "eyy boss";
    }
}

and use it like

var whatisthisidonteven = HurfDurf.Hurr.Wat();

No you can't. In the background enum are value-types (eg just an int).

Eg you can do int i = (int)yourEnum; and vice versa.

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