enum 转 string 忽略前缀

Xcoder 2011-10-27 10:07:41

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

enum eFileType{
eFT_exe,
eFT_dll,
eFT_txt
}
...全文
139 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
aimymi 2011-10-29
  • 打赏
  • 举报
回复
每个枚举值都含有一个"_"
可以跟据indexOf("_")和str.length来截取字符串,这样子就不用关心后缀有几位,或者"_"前面有几位字符了


string str=eFileType.eFT_exe.ToString(); //以字符串的形式返回枚举内某种情况的值

string value=str.Substring(IndexOf("_"),str.length-1);

//str.Substring("要截取的开始位置","要截取的结束位置");可以去搜索一些关于Substring的方法进行扩展;
//很久没用过IndexOf()方法了,有点忘了具体情况,还得麻烦你自己试一下,然后根据情况在+1或者-1;

也可以用匹配啊!
当然情况会比较复杂啦!
阿非 2011-10-29
  • 打赏
  • 举报
回复

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));
effun 2011-10-29
  • 打赏
  • 举报
回复
我认为这种前缀在定义常量中是有必要的,但在枚举里使用就似乎有些画蛇添足了。如果确实需要这样做,可以在转换为字符串以后用SubString截掉前缀:

eFileType.eFT_exe.ToString().SubString(4);

  • 打赏
  • 举报
回复
可以截取拼接
或者反射附加特性
sdl2005lyx 2011-10-29
  • 打赏
  • 举报
回复
这样做:

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 ;
}

wsxqaz 2011-10-27
  • 打赏
  • 举报
回复
直接toString()自己截,这个没有什么好方法,你不知道具体那一段是前缀

110,539

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧