Home > Article > Backend Development > Example of conversion between enum and string in C#
This article mainly introduces the relevant information on the mutual conversion of enum and string in C#. Friends in need can refer to
##C# Json conversion operation
Enumeration type
Enum provides a base class for enumeration. Its base type can be any integer except Char. If it is not explicitly If you want to declare the base type in a formula, use Int32.Note: The base type of the enumeration type is any integer type except
Char, so the value of the enumeration type is an integer type Value1. C# converts the enumeration to a string (enume->string)Our object contains the enumeration type, which is displayed when serialized into a Json string. Is the number corresponding to the enumeration type. Because this is the essence of enumerations, but many times it is necessary to do some operations during JSON conversion to display strings because users need strings. The method is: add attribute tags to the enumeration type[JsonConverter(typeof(StringEnumConverter))]For example: 1), when defining the enumeration type Just declare an attribute on the typeReference Json.net on the MODEL projectDLLThen add Attribute [JsonConverter(typeof(StringEnumConverter))]eg:
public enum RecipientStatus { Sent, Delivered, Signed, Declined } public class RecipientsInfoDepartResult { [JsonConverter(typeof(StringEnumConverter))] //属性将枚举转换为string public RecipientStatus status { set; get; } public PositionBeanResult PredefineSign { set; get; } }2), using Enum’s static methods GetName and GetNames
eg : public static string GetName(Type enumType,Object value) public static string[] GetNames(Type enumType)For example:
Enum.GetName(typeof(Colors),3))与Enum.GetName(typeof(Colors), Colors.Blue))的值都是"Blue" Enum.GetNames(typeof(Colors))将返回枚举字符串数组3), RecipientStatus ty = RecipientStatus.Delivered;
ty.ToString();2, String conversion For example (string->enum)1), use Enum’s static method 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 enumeration type
protected static T GetType<T>(string strType) { T t = (T)Enum.Parse(typeof(T), strType); return t; }Determine whether an enumeration variable is in the definition:
RecipientStatus type = RecipientStatus.Sent; Enum.IsDefined(typeof(RecipientStatus), type );
Summary
The above is the detailed content of Example of conversion between enum and string in C#. For more information, please follow other related articles on the PHP Chinese website!