小编给大家分享一下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的相互转换的示例方法”有了一定的了解,如果想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
网络异常,请检查网络