定义enum 值时,常会加一些前缀,如果想在转 string,或从string 读时,自动忽略前缀,有啥好方法么?

enum eFileType{
 eFT_exe,
 eFT_dll,
 eFT_txt
}

解决方案 »

  1.   

    直接toString()自己截,这个没有什么好方法,你不知道具体那一段是前缀
      

  2.   

    这样做:public enum eFileType{
      [Description("exe")]eFT_exe,
      [Description("dll")]eFT_dll,
      [Description("txt")]eFT_txt
    }public string GetChartset(eFileType filetype)
    {
         FieldInfo fi = filetype.GetType().GetField(filetype.ToString()); 
         DescriptionAttribute[] descriptions = 
         (DescriptionAttribute[])fi.GetCustomAttributes(
         typeof(DescriptionAttribute), false);     if (descriptions == null || descriptions.Length < 1)
         {
             throw new Exception("MailCharset type error.") ;
          }     return descriptions[0].Description ;
    }
      

  3.   

    我认为这种前缀在定义常量中是有必要的,但在枚举里使用就似乎有些画蛇添足了。如果确实需要这样做,可以在转换为字符串以后用SubString截掉前缀:eFileType.eFT_exe.ToString().SubString(4);
      

  4.   


    public static class Extensions
        {
            public static string ToString(this eFileType e, int flag)
            {
                switch (flag)
                {
                    case 0:                    
                        return e.ToString().TrimStart("eFT_".ToArray());
                    default:
                        return e.ToString();
                }
            }
        }Console.WriteLine(eFileType.eFT_dll.ToString(0));
      

  5.   

    每个枚举值都含有一个"_"
    可以跟据indexOf("_")和str.length来截取字符串,这样子就不用关心后缀有几位,或者"_"前面有几位字符了
    string str=eFileType.eFT_exe.ToString();       //以字符串的形式返回枚举内某种情况的值string value=str.Substring(IndexOf("_"),str.length-1);//str.Substring("要截取的开始位置","要截取的结束位置");可以去搜索一些关于Substring的方法进行扩展;
    //很久没用过IndexOf()方法了,有点忘了具体情况,还得麻烦你自己试一下,然后根据情况在+1或者-1;也可以用匹配啊!
    当然情况会比较复杂啦!