This article mainly introduces the conversion of Enum and string in C # related data, the need for friends can refer to the following
C # JSON conversion operations
Enum type
Enum provides a base class for enumerations, which can be of the base type except
Any integral type outside of Char, using Int32 if the underlying type is not explicitly declared.
Note: The base type of the enumeration type is in addition to the
Any integral type outside of Char, so the value of the enumeration type is an integer value
1. C # Converts an enumeration to a string (enume->string)
Our object contains an enumeration type, and when serialized to a JSON string, displays the number corresponding to the enumeration type. Because this is an enumeration
The essence, but many times it is necessary to do something in JSON conversion to display the string because the user needs the string.
By adding a property label on the enumeration type
[Jsonconverter (typeof (Stringenumconverter))]
Examples are as follows:
1), declare an attribute on the type when defining the enumeration type
Referencing Json.NET on Model project
Dll
Then add attribute [Jsonconverter (typeof (Stringenumconverter))]
eg
Public Enumrecipientstatus{sent,delivered,signed,declined}public Classrecipientsinfodepartresult{[jsonconverter ( typeof (Stringenumconverter))]//property converts the enumeration to Stringpublic recipientstatus status {set; get;} Public Positionbeanresult predefinesign {set; get;}}
2), using the static method of enum GetName and GetNames
Eg:public staticstring GetName (type enumtype,object value) public static string[] GetNames (type enumtype)
For example:
The values of Enum.getname (typeof (Colors), 3)) and Enum.getname (typeof (Colors), colors.blue) are all "Blue" Enum.getnames (typeof (Colors ) will return an array of enumerated strings
3), recipientstatus ty = recipientstatus.delivered;
Ty. ToString ();
2. String-to-enumerate (string->enum)
1), static method of using Enum Parse:Enum.Parse ()
Prototype:
public static Object Parse (Type enumtype,string value) eg: (Colors) Enum.parse (typeof (Colors), "Red");(T) Enum.parse ( typeof (T), strtype)
A template function supports any enum type
Protected Statict gettype<t> (string strtype) {T t = (t) enum.parse (typeof (T), strtype); return T;}
Determine if an enumeration variable is in the definition:
Recipientstatus type = recipientstatus.sent; Enum.isdefined (typeof (Recipientstatus), type);
Summarize