简体   繁体   中英

Static construction methods for enums in C#

I'm trying to add static methods to a C# enum. By adding a static class , I can create a 'getter' method, which converts the enum value in eg a byte. However, I cannot seem to make a 'construction' method, which takes the byte and converts it into an enum. In java, I would use the below code without the separate static class.

Enum code:

public enum PoseLocation {

  UP,
  DOWN,
  LEFT,
  RIGHT,
  UP_LEFT,
  UP_RIGHT,
  DOWN_LEFT,
  DOWN_RIGHT

}

public static class PoseLocationMethods {

  public static byte toByte (this PoseLocation location) {
    return (byte)location;
  }

  public static PoseLocation fromByte (byte poseByte) {
    return (PoseLocation)poseByte;
  }

}

Method calls:

byte poseByte = PoseLocation.UP.toByte (); //OK
PoseLocation fromByte = PoseLocation.fromByte (poseByte); //this does not work

You seem to think that fromByte is also an extension method...

Look at the declaration carefully:

public static PoseLocation fromByte (byte poseByte)

Do you see the word this ? No. So it's not an extension method. It's just a normal static method like any other. To call a static method, you need to put the class in which it is declared in in front. In this case, fromByte is declared in PoseLocationMethods , so you should do:

PoselocationMethods.fromByte(1);

However, I don't think fromByte belongs to the PoseLocationMethods class. You might want to write an extension method for byte :

public static PoseLocation ToPoseLocation(this byte poseByte) {
    return (Poselocation)poseByte;
}

Alternatively, get rid of these To and From methods. I think using a cast is clear enough.

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