从常量字段中提取描述属性 [英] Extract Description Attribute from Const Fields

查看:54
本文介绍了从常量字段中提取描述属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Base on This Answer, I can get description attribute from class Property as follow:

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

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

I can get Description value, as follow:

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

现在,发生了什么变化,我必须在此助手中执行以下操作才能从 cosnt fields 中获取描述,如下所示:

and now, What changes Must I do in this helper to get description from cosnt fields as follow:

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

推荐答案

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

Getting value of objects const field by reflection:

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

这篇关于从常量字段中提取描述属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆