C# Enum,Int,String的互相转换

简介: 原文:C# Enum,Int,String的互相转换【C# Enum,Int,String的互相转换】 1、Enum-->String (1)利用Object.ToString()方法:如Colors.
原文: C# Enum,Int,String的互相转换

C# Enum,Int,String的互相转换

1、Enum-->String

(1)利用Object.ToString()方法:如Colors.Green.ToString()的值是"Green"字符串;
(2)利用Enum的静态方法GetName与GetNames:
   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))将返回枚举字符串数组。

2、String-->Enum

(1)利用Enum的静态方法Parse:
   public static Object Parse(Type enumType,string value)
   例如:(Colors)Enum.Parse(typeof(Colors), "Red")

3、Enum-->Int

(1)因为枚举的基类型是除 Char 外的整型,所以可以进行强制转换。
   例如:(int)Colors.Red, (byte)Colors.Green

4、Int-->Enum

(1)可以强制转换将整型转换成枚举类型。
   例如:Colors color = (Colors)2 ,那么color即为Colors.Blue
(2)利用Enum的静态方法ToObject。
   public static Object ToObject(Type enumType,int value)
   例如:Colors color = (Colors)Enum.ToObject(typeof(Colors), 2),那么color即为Colors.Blue

5、判断某个整型是否定义在枚举中的方法:Enum.IsDefined

public static bool IsDefined(Type enumType,Object value)
例如:Enum.IsDefined(typeof(Colors), n))

参考:

1、http://msdn.microsoft.com/zh-cn/library/system.enum(v=vs.110).aspx

2、http://www.cnblogs.com/myx/archive/2011/06/17/Enum-Int-String.html

 

 

 

 

 

 

 

 

 

 

目录
相关文章
|
1月前
|
C#
51.c#:string类的静态方法
51.c#:string类的静态方法
20 1
|
5月前
|
Go
go string to int 字符串与整数型的互换
go string to int 字符串与整数型的互换
34 0
|
1月前
|
C#
深入C#中的String类
深入C#中的String类
11 0
|
1月前
|
C#
C# 字节数组与INT16,float,double之间相互转换,字符数组与字符串相互转换,
C# 字节数组与INT16,float,double之间相互转换,字符数组与字符串相互转换,
37 1
|
1月前
|
Python
Python系列(15)—— int类型转string类型
Python系列(15)—— int类型转string类型
|
1月前
|
自然语言处理 C# 数据安全/隐私保护
50.c#:string类初始化
50.c#:string类初始化
12 1
|
1月前
|
开发框架 .NET C#
C# Dictionary<string, string> 对key做筛选
C# Dictionary<string, string> 对key做筛选
17 2
|
6月前
|
Java
【Java用法】Java中String类型和int类型互转的所有方法
【Java用法】Java中String类型和int类型互转的所有方法
78 0
|
7月前
|
自然语言处理 C# 数据格式
C#OOP之十五 String类&StringBuilder类
C#OOP之十五 String类&StringBuilder类
22 0
|
8月前
|
Java
Java int 与 String 的互相转换
Java int 与 String 的互相转换
42 0