我是靠谱客的博主 风中往事,这篇文章主要介绍C#中enum与string的相互转换的示例,现在分享给大家,希望可以做个参考。

这篇文章主要介绍了C#中enum和string的相互转换的相关资料,需要的朋友可以参考下

C# Json转换操作

枚举类型

Enum为枚举提供基类,其基础类型可以是除

Char 外的任何整型,如果没有显式声明基础类型,则使用Int32。

注意:枚举类型的基类型是除

Char 外的任何整型,所以枚举类型的值是整型值

1、C#将枚举转为字符串(enume->string)

我们的对象中包含枚举类型,在序列化成Json字符串的时候,显示的是枚举类型对应的数字。因为这是枚举的

本质所在,但是很多时候需要在JSON转化的时候做一些操作,使之显示字符串,因为用户需要字符串。

方法就是:在枚举类型上添加属性标签


复制代码
1
[JsonConverter(typeof(StringEnumConverter))]
登录后复制

举例如下:

1)、在定义枚举类型时在类型上声明一个属性即可

在MODEL project上引用Json.net

DLL

然后加上Attribute [JsonConverter(typeof(StringEnumConverter))]

eg:


复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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


复制代码
1
2
3
eg : public static string GetName(Type enumType,Object value) public static string[] GetNames(Type enumType)
登录后复制

例如:


复制代码
1
2
3
Enum.GetName(typeof(Colors),3))与Enum.GetName(typeof(Colors), Colors.Blue))的值都是"Blue" Enum.GetNames(typeof(Colors))将返回枚举字符串数组
登录后复制

3)、RecipientStatus ty = RecipientStatus.Delivered;


复制代码
1
ty.ToString();
登录后复制

2、字符串转枚举(string->enum)

1)、利用Enum的静态方法Parse: Enum.Parse()

原型:


复制代码
1
2
3
4
public static Object Parse(Type enumType,string value) eg : (Colors)Enum.Parse(typeof(Colors), "Red"); (T)Enum.Parse(typeof(T), strType)
登录后复制

一个模板函数支持任何枚举类型


复制代码
1
2
3
4
5
6
7
protected static T GetType<T>(string strType) { T t = (T)Enum.Parse(typeof(T), strType); return t; }
登录后复制

判断某个枚举变量是否在定义中:


复制代码
1
2
3
4
RecipientStatus type = RecipientStatus.Sent; Enum.IsDefined(typeof(RecipientStatus), type );
登录后复制

总结

以上就是C#中enum与string的相互转换的示例的详细内容,更多请关注靠谱客其它相关文章!

最后

以上就是风中往事最近收集整理的关于C#中enum与string的相互转换的示例的全部内容,更多相关C#中enum与string内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(120)

评论列表共有 0 条评论

立即
投稿
返回
顶部