从常量字段中提取描述属性

Ami*_*mir 6 c# reflection

基于此答案,我可以从类中获取描述属性,Property如下所示:

public class A
{
    [Description("My Property")]
    public string MyProperty { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我可以获得Description价值,如下:

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

现在,我必须在此帮助程序中进行哪些更改才能获取描述,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);
Run Code Online (Sandbox Code Playgroud)

And*_*sok 6

通过反射获取对象 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

例子:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)