把Enum与Int32、String的相互转换的代码

简介:

平时我们须要把Enum类型与int(或者string)类型进行相互转换,利用下面的泛型编程,可以处理所有情况了。

 
 
  1. public static class EnumHelper2<T> 
  2.     public static String Enum2String(T value) 
  3.     { 
  4.         return value.ToString(); 
  5.     } 
  6.  
  7.     public static T String2Enum(string value, bool ignoreCase) 
  8.     { 
  9.         return (T)Enum.Parse(typeof(T), value, ignoreCase); 
  10.     } 
  11.  
  12.     public static int Enum2Int(T value) 
  13.     { 
  14.         return Convert.ToInt32(value); 
  15.     } 
  16.  
  17.     public static T Int2Enum(int value) 
  18.     { 
  19.         if (Enum.IsDefined(typeof(T), value)) 
  20.             return (T)Enum.ToObject(typeof(T), value); 
  21.         else 
  22.             throw new Exception(value + " is not defined"); 
  23.     } 
  24.  
  25. public static class EnumHelper 
  26.     public static int ToInt32<T>(T value) 
  27.     { 
  28.         return Convert.ToInt32(value); 
  29.     } 
  30.  
  31.     public static T FromInt32<T>(int value) 
  32.     { 
  33.         return (T)Enum.ToObject(typeof(T), value); 
  34.     } 
  35.  
  36.     public static T Parse<T>(string value, bool ignoreCase) 
  37.     { 
  38.         if (Enum.IsDefined(typeof(T), value)) 
  39.             return (T)Enum.Parse(typeof(T), value, ignoreCase); 
  40.         else 
  41.             throw new Exception(value + " is not defined"); 
  42.     } 
  43.  
  44.     public static T Parse<T>(int value) 
  45.     { 
  46.         if (Enum.IsDefined(typeof(T), value)) 
  47.             return (T)Enum.ToObject(typeof(T), value); 
  48.         else 
  49.             throw new Exception(value + " is not defined"); 
  50.     } 









本文转自 h2appy  51CTO博客,原文链接:http://blog.51cto.com/h2appy/412021,如需转载请自行联系原作者
目录
相关文章
|
6月前
|
Go
go string to int 字符串与整数型的互换
go string to int 字符串与整数型的互换
36 0
|
1天前
int 和 String 互相转换的多种方法
int 和 String 互相转换的多种方法
|
1天前
|
Python
Python系列(15)—— int类型转string类型
Python系列(15)—— int类型转string类型
|
7月前
|
Java
【Java用法】Java中String类型和int类型互转的所有方法
【Java用法】Java中String类型和int类型互转的所有方法
80 0
|
9月前
|
Java
Java int 与 String 的互相转换
Java int 与 String 的互相转换
44 0
|
1天前
|
C++ 容器
【C++】STL容器——string类的使用指南(含代码演示)(8)
【C++】STL容器——string类的使用指南(含代码演示)(8)
|
1天前
|
C# 图形学
【Unity 3D】C#中String类的介绍及字符串常用操作详解(附测试代码 超详细)
【Unity 3D】C#中String类的介绍及字符串常用操作详解(附测试代码 超详细)
89 0
|
1天前
|
Python
modelscope通义千问的14b量化版出错 说没有版本 这个代码都是从页面上粘贴下来的 Int8 Int4都试过了一样的错误?
modelscope通义千问的14b量化版出错 说没有版本 这个代码都是从页面上粘贴下来的 Int8 Int4都试过了一样的错误?modelscope.hub.errors.NoValidRevisionError: The model: qwen/Qwen-14B-Chat-Int4 has no valid revision!
322 1
|
5月前
|
Python
TypeError: int() argument must be a string, a bytes原因
Python开发过程中,使用int()函数来转换或生成int类型的数据时,如果Python抛出并提示TypeError: int() argument must be a string, a bytes-like object or a real number, not 'complex',那么原因在于传递给int()函数的参数类型有误,正如TypeError的提示,int()函数的参数必须是string字符串(数值字符串)、类似字节对象、real number数字等,而不可以是complex复数类型的数据。
123 0