C# enum和string的轉換
C# Json轉換操作
枚舉類型
Enum爲枚舉提供基類,其基礎類型可以是除Char
外的任何整型,如果沒有顯式聲明基礎類型,則使用Int32。
注意:枚舉類型的基類型是除Char
外的任何整型,所以枚舉類型的值是整型值
1、C#將枚舉轉爲字符串(enume->string)
我們的對象中包含枚舉類型,在序列化成Json字符串的時候,顯示的是枚舉類型對應的數字。因爲這是枚舉的
本質所在,但是很多時候需要在JSON轉化的時候做一些操作,使之顯示字符串,因爲用戶需要字符串。
方法就是:在枚舉類型上添加屬性標籤
[JsonConverter(typeof(StringEnumConverter))]
舉例如下:
1)、在定義枚舉類型時在類型上聲明一個屬性即可
在MODEL project上引用Json.netDLL
然後加上Attribute [JsonConverter(typeof(StringEnumConverter))]
eg:
public enumRecipientStatus
{
[JsonConverter(typeof(StringEnumConverter))]
Sent,
[JsonConverter(typeof(StringEnumConverter))]
Delivered,
[JsonConverter(typeof(StringEnumConverter))]
Signed,
[JsonConverter(typeof(StringEnumConverter))]
Declined
}
當然你還要加上命名空間, using Newtonsoft.Json.Linq;之類的東西,快捷鍵 Alt + F10,自動添加。public classRecipientsInfoDepartResult
{
[JsonConverter(typeof(StringEnumConverter))]//屬性將枚舉轉換爲string
public RecipientStatus status {set;
get; }
public PositionBeanResult PredefineSign {set;
get; }
}
2)、利用Enum的靜態方法GetName與GetNames
eg : public staticstring
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))將返回枚舉字符串數組
3)、RecipientStatus ty = RecipientStatus.Delivered;
ty.ToString();
2、字符串轉枚舉(string->enum)
1)、利用Enum的靜態方法Parse: Enum.Parse()
原型:public static Object Parse(Type enumType,string value)
eg : (Colors)Enum.Parse(typeof(Colors), "Red");
(T)Enum.Parse(typeof(T),strType)
一個模板函數支持任何枚舉類型
protected staticT
GetType<T>(string strType)
{
T t = (T)Enum.Parse(typeof(T),strType);
return t;
}
判斷某個枚舉變量是否在定義中:
RecipientStatus type =
RecipientStatus.Sent;
Enum.IsDefined(typeof(RecipientStatus),type );
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.