当前位置: 移动技术网 > IT编程>开发语言>c# > C#中enum和string的相互转换

C#中enum和string的相互转换

2019年07月18日  | 移动技术网IT编程  | 我要评论
c# json转换操作 枚举类型 enum为枚举提供基类,其基础类型可以是除 char 外的任何整型,如果没有显式声明基础类型,则使用int32。 注意:枚举类型的

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的相互转换,希望对大家有所帮助

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网