简体   繁体   中英

Parameter Enums in C#

I'm used to programming in Java however for this project I'm supposed to be using C#, I'm trying to convert my Packet system over from my Java project, however I'm running into some issues using the C# Compiler. Here's the code.

abstract class Packet
{
    public static enum PacketTypes
    {
        INVALID(-1), LOGIN(00);

        private int packetId;

        private PacketTypes(int packetId)
        {
            this.packetId = packetId;
        }

        public int getId()  { return packetId; }

    }
}

This is actually exactly how it's done in my Java Code, and I have the individual packets extend the Packet class. I'm trying to figure out how to make this all come together in C#. Perhaps having a separate class for each packet isn't the way it should be done here?

I'm not sure what you're trying to achieve, but you can set values for particular enum elements in C#:

public enum PacketTypes
{
    INVALID = -1;
    LOGIN = 0;
}

Because enum is by default backed by int , you can cast it from/to int without additional code.

enum s in C# cannot content any members, so you can't add methods/properties/fields to enum declaration.

Unlike Java where enum s are classes, in C# enum s are plain values. They cannot have member functions or fields.

One approach that could help is to define an extension method for your enum , like this:

public static class PacketTypesExtensions {
    static readonly IDictionary<PacketTypes,int> IdForType = new Dictionary<PacketTypes,int> {
        { PacketTypes.INVALID, -1 }
    ,   { PacketTypes.LOGIN,    0 }
    };
    static readonly IDictionary<PacketTypes,string> DescrForType = new Dictionary<PacketTypes,string> {
        { PacketTypes.INVALID, "<invalid packet type>" }
    ,   { PacketTypes.LOGIN,   "<user login>" }
    };
    public static string Description(this PacketTypes t) {
        return DescrForType[t];
    }
    public static int Id(this PacketTypes t) {
        return IdForType[t];
    }
}

This lets you keep Java syntax:

PacketTypes pt = ... // <<== Assign a packet type here
int id = pt.Id();    // This calls the static extension method
string d = pt.Description();

You could try this in addition to Marcins answer.

public enum PacketTypes
{
    INVALID = -1;
    LOGIN = 0;
}

public class Packet
{
    public PacketTypes PacketType { get; set;}
}

In your code somewhere, you would do this

public void DoSomething()
{
    var packet = new Packet();
    packet.PacketType = PacketTypes.INVALID; // Assign packtype
    Console.WriteLine(packet.PacketType.ToString()); // Retrieve and print 
}

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