C#中enum與string的相互轉換的範例

黄舟
發布: 2017-09-05 14:36:00
原創
2008 人瀏覽過

這篇文章主要介紹了C#中enum和string的相互轉換的相關資料,需要的朋友可以參考下

C# Json轉換操作

枚舉類型

Enum為枚舉提供基類,其基礎型別可以是除

Char 以外的任何整數,如果沒有顯式聲明基礎類型,則使用Int32。

注意:枚舉類型的基底類型是除

#Char 外的任何整數,所以枚舉類型的值是整數值

1、C#將枚舉轉為字串(enume->string)

我們的物件中包含枚舉類型,在序列化成Json字串的時候,顯示的是枚舉類型對應的數字。因為這是枚舉的

本質所在,但是很多時候需要在JSON轉換的時候做一些操作,使之顯示字串,因為使用者需要字串。

方法是:在枚舉類型上新增屬性標籤


[JsonConverter(typeof(StringEnumConverter))]
登入後複製

舉例如下:

1)、在定義枚舉類型時在型別上宣告一個屬性即可

在MODEL project上引用Json.net

DLL

然後加上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)、利用Enum的靜態方法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))将返回枚举字符串数组
登入後複製

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 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 );
登入後複製

總結

#

以上是C#中enum與string的相互轉換的範例的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!