简体   繁体   中英

Enum to Class in C#

I have one Enum like this:

public enum CommonMessage : ushort
{
    val =1,
    val2 = 2,
    val3 = 3
 }

I have to send this data to other application. Communication is happening between my application and other through comport(serialCommunication).

I'm getting back to data to my application also .

I want convert this Enum to class. Please tell me how Can I do this. what should be the data type of the variables.

An enum is basically a set of named constants that represent numbers. So you can just convert the type to it's numeric equivalent and then convert whatever is returned back accordingly. So if you wanted to pass the value to an application, you could convert the enum to it's numeric type:

var myEnumNumericValue = (ushort)CommonMessage.val; //would represent "CommonMessage.val" 

When your application sends back a value it would be a number, and you can convert it back accordingly:

var enumValue = (CommonMessage)returnValue; //where return value is an ushort

If you MUST send class, send an Int32 - it is the smallest form of an enum value.

Your connected client can parse that locally allowing for different technologies, ie a JavaScript client could implement a matching enum or you could use a reference to the same enum in a .Net client. Either way, it should still be an int and easy to transfer.

Hope that helps.

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