这篇文章主要介绍了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的相互转换的示例的详细内容,更多请关注Work网其它相关文章!

08-31 09:37