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的相互转换,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对我们网站的支持!
您可能感兴趣的文章
- 01-10C#通过反射获取当前工程中所有窗体并打开的方法
- 01-10C#实现Winform中打开网页页面的方法
- 01-10C#实现由四周向中心缩小的窗体退出特效
- 01-10Extjs4如何处理后台json数据中日期和时间
- 01-10C#中DataGridView常用操作实例小结
- 01-10C#编程获取资源文件中图片的方法
- 01-10asp.net中XML如何做增删改查操作
- 01-10C#利用反射技术实现去掉按钮选中时的边框效果
- 01-10C#中查找Dictionary中的重复值的方法
- 01-10C#及WPF获取本机所有字体和颜色的方法
阅读排行
本栏相关
- 01-10C#通过反射获取当前工程中所有窗体并
- 01-10关于ASP网页无法打开的解决方案
- 01-10WinForm限制窗体不能移到屏幕外的方法
- 01-10WinForm绘制圆角的方法
- 01-10C#实现txt定位指定行完整实例
- 01-10WinForm实现仿视频播放器左下角滚动新
- 01-10C#停止线程的方法
- 01-10C#实现清空回收站的方法
- 01-10C#通过重写Panel改变边框颜色与宽度的
- 01-10C#实现读取注册表监控当前操作系统已
随机阅读
- 04-02jquery与jsp,用jquery
- 01-10delphi制作wav文件的方法
- 08-05织梦dedecms什么时候用栏目交叉功能?
- 08-05DEDE织梦data目录下的sessions文件夹有什
- 01-10SublimeText编译C开发环境设置
- 01-10使用C语言求解扑克牌的顺子及n个骰子
- 01-11ajax实现页面的局部加载
- 01-11Mac OSX 打开原生自带读写NTFS功能(图文
- 08-05dedecms(织梦)副栏目数量限制代码修改
- 01-10C#中split用法实例总结