从构造字段中提取描述属性



基于这个答案,我可以从类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);

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

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

相关内容

  • 没有找到相关文章

最新更新