Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract Description Attribute from Const Fields

Tags:

c#

reflection

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

I can get Description value, as follow:

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

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);
like image 328
Amir Avatar asked Nov 02 '15 20:11

Amir


1 Answers

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

Example:

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);
    }
}
like image 90
Andrii Tsok Avatar answered Oct 19 '22 04:10

Andrii Tsok