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))]
public enum RecipientStatus { Sent, Delivered, Signed, Declined } public class RecipientsInfoDepartResult { [JsonConverter(typeof(StringEnumConverter))] //属性将枚举转换为string public RecipientStatus status { set; get; } public PositionBeanResult PredefineSign { set; get; } }
eg : public static string GetName(Type enumType,Object value) public static string[] GetNames(Type enumType)
Enum.GetName(typeof(Colors),3))与Enum.GetName(typeof(Colors), Colors.Blue))的值都是"Blue" Enum.GetNames(typeof(Colors))将返回枚举字符串数组
ty.ToString();
public static Object Parse(Type enumType,string value) eg : (Colors)Enum.Parse(typeof(Colors), "Red"); (T)Enum.Parse(typeof(T), strType)
protected static T GetType<T>(string strType) { T t = (T)Enum.Parse(typeof(T), strType); return t; }
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!