从Const字段中提取描述属性

时间:2015-11-02 20:06:25

标签: c# reflection

Base on This Answer,我可以从类Property获取描述属性,如下所示:

public class A
{
    [Description("My Property")]
    public string MyProperty { get; set; }
}

我可以获得Description值,如下所示:

// result: My Property
var foo = AttributeHelper.GetPropertyAttributeValue<A, string, DescriptionAttribute, string>(x => x.MyProperty, y => y.Description);

现在,会发生什么变化我必须在此帮助程序中从cosnt fields获取说明,如下所示:

public class A
{
    [Description("Const Field")]
    public const string ConstField = "My Const";
}

// output: Const Field
var foo = AttributeHelper.GetPropertyAttributeValue<A, string, DescriptionAttribute, string>(x => x.ConstField, y => y.Description);

1 个答案:

答案 0 :(得分:1)

通过反射获取对象const字段的值:

using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

public static class AttributeHelper
{
    public static TOut GetConstFieldAttributeValue<T, TOut, TAttribute>(
        string fieldName,
        Func<TAttribute, TOut> valueSelector)
        where TAttribute : Attribute
    {
        var fieldInfo = typeof(T).GetField(fieldName, BindingFlags.Public | BindingFlags.Static);
        if (fieldInfo == null)
        {
            return default(TOut);
        }
        var att = fieldInfo.GetCustomAttributes(typeof(TAttribute), true).FirstOrDefault() as TAttribute;
        return att != null ? valueSelector(att) : default(TOut);
    }
}

示例:

public class A
{
    [Description("Const Field")]
    public const string ConstField = "My Const";
}

class Program
{

    static void Main(string[] args)
    {
        var foo = AttributeHelper.GetConstFieldAttributeValue<A, string, DescriptionAttribute>("ConstField", y => y.Description);

        Console.WriteLine(foo);
    }
}