代码改变世界

枚举类型和int以及string的相互转换

  Virus-BeautyCode  阅读(2385)  评论(0编辑  收藏  举报

 

  假如我们现在有一个枚举类型

  

复制代码
枚举
/// <summary>
    
/// 用户类型
    
/// </summary>
    public enum UserTypeEnum
    {
        
/// <summary>
        
/// 匿名用户
        
/// </summary>
        Anonymous = 1,
        
/// <summary>
        
/// 学生
        
/// </summary>
        Student,
        
/// <summary>
        
/// 教师
        
/// </summary>
        Teacher,
        /// <summary>
        
///系统平台 
        
/// </summary>
        SystemPlatform

    }
复制代码

 

  

  类型转换工具类

  

复制代码
代码
/// <summary>
    
/// 用户类型转换,枚举类型和int、string类型的转换
    
/// </summary>
    public class UserTypeEnumUtility
    {

        
public static UserTypeEnum String2UserType(string text,bool ignoreCase)
        {
            
return (UserTypeEnum)Enum.Parse(typeof(UserTypeEnum), text,ignoreCase );
        }
        
public static  int UserType2Int(UserTypeEnum userType)
        {
            
return (int)userType ;
        }
        
public static UserTypeEnum Int2UserType(int n)
        {
            
if (Enum.IsDefined(typeof(UserTypeEnum), n))
                
return (UserTypeEnum)n;
            
else
                
throw new Exception(string.Format("{0} is not definded.", n));
        }
        
public static string UserType2String(UserTypeEnum userType)
        {
            
return userType.ToString();
        }
    }
复制代码

 

 

编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示