小編給大家分享一下C#中enum與string的相互轉(zhuǎn)換的示例方法,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
C# Json轉(zhuǎn)換操作
枚舉類(lèi)型
Enum為枚舉提供基類(lèi),其基礎(chǔ)類(lèi)型可以是除
Char 外的任何整型,如果沒(méi)有顯式聲明基礎(chǔ)類(lèi)型,則使用Int32。
注意:枚舉類(lèi)型的基類(lèi)型是除
Char 外的任何整型,所以枚舉類(lèi)型的值是整型值
1、C#將枚舉轉(zhuǎn)為字符串(enume->string)
我們的對(duì)象中包含枚舉類(lèi)型,在序列化成Json字符串的時(shí)候,顯示的是枚舉類(lèi)型對(duì)應(yīng)的數(shù)字。因?yàn)檫@是枚舉的
本質(zhì)所在,但是很多時(shí)候需要在JSON轉(zhuǎn)化的時(shí)候做一些操作,使之顯示字符串,因?yàn)橛脩?hù)需要字符串。
方法就是:在枚舉類(lèi)型上添加屬性標(biāo)簽
[JsonConverter(typeof(StringEnumConverter))]
舉例如下:
1)、在定義枚舉類(lèi)型時(shí)在類(lèi)型上聲明一個(gè)屬性即可
在MODEL project上引用Json.net
DLL
然后加上Attribute [JsonConverter(typeof(StringEnumConverter))]
eg:
public enum RecipientStatus { Sent, Delivered, Signed, Declined } public class RecipientsInfoDepartResult { [JsonConverter(typeof(StringEnumConverter))] //屬性將枚舉轉(zhuǎn)換為string public RecipientStatus status { set; get; } public PositionBeanResult PredefineSign { set; get; } }
2)、利用Enum的靜態(tài)方法GetName與GetNames
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))將返回枚舉字符串?dāng)?shù)組
3)、RecipientStatus ty = RecipientStatus.Delivered;
ty.ToString();
2、字符串轉(zhuǎn)枚舉(string->enum)
1)、利用Enum的靜態(tài)方法Parse: Enum.Parse()
原型:
public static Object Parse(Type enumType,string value) eg : (Colors)Enum.Parse(typeof(Colors), "Red"); (T)Enum.Parse(typeof(T), strType)
一個(gè)模板函數(shù)支持任何枚舉類(lèi)型
protected static T GetType<T>(string strType) { T t = (T)Enum.Parse(typeof(T), strType); return t; }
判斷某個(gè)枚舉變量是否在定義中:
RecipientStatus type = RecipientStatus.Sent; Enum.IsDefined(typeof(RecipientStatus), type );
看完了這篇文章,相信你對(duì)“C#中enum與string的相互轉(zhuǎn)換的示例方法”有了一定的了解,如果想了解更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!
本文名稱(chēng):C#中enum與string的相互轉(zhuǎn)換的示例方法-創(chuàng)新互聯(lián)
網(wǎng)站路徑:http://www.chinadenli.net/article12/disggc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供響應(yīng)式網(wǎng)站、Google、建站公司、移動(dòng)網(wǎng)站建設(shè)、品牌網(wǎng)站制作、小程序開(kāi)發(fā)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話(huà):028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容