public enum Color
{
[ColorText("红色")]
red = 0,
[ColorText("黑色")]
black = 1
}[AttribuateUsage(AttribuateTargets.All)] //这里该怎么写
public class ColorText : Attribuate
{

}然后该如何提取出枚举属性中的ColorText值 GetMembers()得不到这个值enum中得属性该用什么提取出来然后再GetCustomAttributes呢?

解决方案 »

  1.   

    try
    using System;
    using System.Reflection;
    [AttributeUsage(AttributeTargets.All)] 
    public class ColorText : Attribute 
    {
    private string s;
    public ColorText(string s)
    {
    this.s = s;
    } public string Text
    {
    get { return s;}
    }
    }
    public enum Color
    {
    [ColorText("红色")]
    red = 0,
    [ColorText("黑色")]
    black = 1
    }public class TestAtt
    {
    public static void Main()
    {
    Type t = typeof(Color);

    FieldInfo fi = t.GetField("black");

    ColorText ct = (ColorText )fi.GetCustomAttributes(typeof(ColorText), false)[0];
    Console.WriteLine(ct.Text); }
    }
      

  2.   

    actually, following normal conventions, you should name your attribute as ColorTextAttribute
    using System;
    using System.Reflection;
    [AttributeUsage(AttributeTargets.All)] 
    public class ColorTextAttribute : Attribute 
    {
    private string s;
    public ColorTextAttribute(string s)
    {
    this.s = s;
    } public string Text
    {
    get { return s;}
    }
    }
    public enum Color
    {
    [ColorText("红色")]
    red = 0,
    [ColorText("黑色")]
    black = 1
    }public class TestAtt
    {
    public static void Main()
    {
    Type t = typeof(Color);

    FieldInfo fi = t.GetField("black");

    ColorTextAttribute ct = (ColorTextAttribute)fi.GetCustomAttributes(typeof(ColorTextAttribute), false)[0];
    Console.WriteLine(ct.Text); }
    }
      

  3.   

    VB的,凑合看(原理部分是一样的)
    Imports System.Reflection<AttributeUsage(AttributeTargets.Field)> _
    Public Class ColorAttribute
        Inherits Attribute    Public ColorName As String
        Public Sub New(ByVal colorName As String)
            Me.ColorName = colorName
        End Sub
    End ClassPublic Enum EnumTest
        <Color("红色")> red
        <Color("绿色")> green
    End EnumPublic Class Extract
        Public Shared Function ExtractColorName(ByVal x As EnumTest) As String
            Dim t As Type = x.GetType
            Dim field As FieldInfo = t.GetField([Enum].GetName(t, x))        Dim colorName As String = ""
            For Each attr As Attribute In Attribute.GetCustomAttributes(field)
                If TypeOf attr Is ColorAttribute Then
                    colorName = CType(attr, ColorAttribute).ColorName
                End If
            Next        Return colorName
        End FunctionEnd Class
      

  4.   

    原来这东西叫Field啊,谢谢二位!