简体   繁体   English

C#中枚举的静态构造方法

[英]Static construction methods for enums in C#

I'm trying to add static methods to a C# enum. 我正在尝试向C#枚举添加静态方法。 By adding a static class , I can create a 'getter' method, which converts the enum value in eg a byte. 通过添加一个static class ,我可以创建一个“ getter”方法,该方法将枚举值转换为一个字节。 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. 在Java中,我将使用以下代码而不使用单独的静态类。

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... 您似乎认为fromByte也是一种扩展方法...

Look at the declaration carefully: 仔细看一下声明:

public static PoseLocation fromByte (byte poseByte) 公共静态PoseLocation fromByte(字节poseByte)

Do you see the word this ? 你看到这个词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: 在这种情况下, fromBytePoseLocationMethods声明,因此您应该执行以下操作:

PoselocationMethods.fromByte(1);

However, I don't think fromByte belongs to the PoseLocationMethods class. 但是,我认为fromByte属于PoseLocationMethods类。 You might want to write an extension method for byte : 您可能要为byte编写扩展方法:

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

Alternatively, get rid of these To and From methods. 或者,摆脱这些ToFrom方法。 I think using a cast is clear enough. 我认为使用演员表已经足够清楚了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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