关于枚举取值

小白_YY 2009-12-08 03:53:44
public enum HandleInd
{
[Description("已处理")]
Processed = 'Y',
[Description("未处理")]
Untreated = 'N'
}

怎么获取Description 和 值 'Y'
...全文
364 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
bancxc 2009-12-08
  • 打赏
  • 举报
回复
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace Attributes
{
[AttributeUsage(AttributeTargets.All)]
public class DescriptionAttribute : Attribute
{
private string Description;

public DescriptionAttribute(string description)
{
Description = description;
}
public override string ToString()
{
return Description;
}
}

public enum HandleInd
{
[Description("已处理")]
Processed = 'Y',
[Description("未处理")]
Untreated = 'N'
}

public class MainClass
{
static void Main()
{
Type t = typeof(HandleInd);

foreach (MemberInfo t1 in t.GetFields())
{
foreach (object attribute in t1.GetCustomAttributes(false))
{
Console.WriteLine(attribute); //已处理 未处理
}
}

HandleInd h = HandleInd.Processed;
char a = (char)h;
Console.WriteLine(a); //Y

h = HandleInd.Untreated;
a= (char)h;
Console.WriteLine(a); //N

Console.ReadLine();
}
}
//已处理
//未处理
//Y
//N
}
tangsan1985 2009-12-08
  • 打赏
  • 举报
回复
同样存在这样的问题,学习了
andyalex 2009-12-08
  • 打赏
  • 举报
回复
反射
sdjmu 2009-12-08
  • 打赏
  • 举报
回复
同意5楼
liherun 2009-12-08
  • 打赏
  • 举报
回复
泛型和反射得好好学学了
liherun 2009-12-08
  • 打赏
  • 举报
回复
wartim老大,又反射?
wartim 2009-12-08
  • 打赏
  • 举报
回复
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication212
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();

DescriptionAttribute DA = (DescriptionAttribute)this.GetType()
.GetNestedType("HandleInd").GetField("Processed")
.GetCustomAttributes(typeof(DescriptionAttribute), false)[0];
MessageBox.Show(DA.Description);
}

public enum HandleInd
{
[Description("已处理")]
Processed = 'Y',
[Description("未处理")]
Untreated = 'N'
}
}
}
babyofbaby 2009-12-08
  • 打赏
  • 举报
回复
先加一个枚举转换成键值对的方法:
public static NameValueCollection ConvertEnumDescriptionValue()
{

NameValueCollection nvc = new NameValueCollection();
Type type = typeof(DescriptionAttribute);

foreach (FieldInfo fi in typeof(HandleInd).GetFields())
{
object[] arr = fi.GetCustomAttributes(type, true);
if (arr.Length > 0)
{

nvc.Add(fi.Name, ((DescriptionAttribute)arr[0]).Description);
}
}

return nvc;

}

然后调用:
ConvertEnumDescriptionValue().GetValues(0)[0],就取到“已处理”了,另一个类似。

要取"Y",直接用(char)HandleInd.Processed
liherun 2009-12-08
  • 打赏
  • 举报
回复
学习下
小白_YY 2009-12-08
  • 打赏
  • 举报
回复
Enum.Parse()
Enum.GetValues()
取的不 是'Y'
zr2199 2009-12-08
  • 打赏
  • 举报
回复
HandleInd.Processed

110,567

社区成员

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

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

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