Extract Description Attribute from Const Fields

后端 未结 1 648
借酒劲吻你
借酒劲吻你 2021-01-24 03:30

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

public class A
{
    [Description(\"My Property\")]
    public s         


        
1条回答
  •  -上瘾入骨i
    2021-01-24 04:05

    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(
            string fieldName,
            Func 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);
        }
    }
    

    Example:

    public class A
    {
        [Description("Const Field")]
        public const string ConstField = "My Const";
    }
    
    class Program
    {
    
        static void Main(string[] args)
        {
            var foo = AttributeHelper.GetConstFieldAttributeValue("ConstField", y => y.Description);
    
            Console.WriteLine(foo);
        }
    }
    

    0 讨论(0)
提交回复
热议问题