简体   繁体   English

在C#中枚举到类

[英]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). 我的应用程序和其他应用程序之间通过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. 如果必须发送类,则发送Int32-它是枚举值的最小形式。

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. 您连接的客户端可以在本地解析该代码,以允许使用不同的技术,即JavaScript客户端可以实现匹配的枚举,或者您可以在.Net客户端中使用对同一枚举的引用。 Either way, it should still be an int and easy to transfer. 无论哪种方式,它都应该仍然是int且易于传输。

Hope that helps. 希望能有所帮助。

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

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