mardi 3 octobre 2017

Dynamic Enum with runtime attributes definition in C#

I have created the enum at run-time using reflection as dictated in this link. Dynamic Enum in C#

My current custom attribute definition as below:

public interface IAttribute<out T>
{
    T Value { get; }
}

public sealed class FormNameAttribute : Attribute, IAttribute<string>
{
    public FormNameAttribute(string value)
    {
        Value = value;
    }

    public string Value { get; }
}

public sealed class FormCaptionAttribute : Attribute, IAttribute<string>
{
    public FormCaptionAttribute(string value)
    {
        Value = value;
    }

    public string Value { get; }
}

public static class EnumExtensions
{
    public static TR GetAttributeValue<T, TR>(this Enum value) //T :- CustomAttribute, TR :- Custom Attribute Type
    {
        var attributeValue = default(TR);

        if (value == null) return attributeValue;
        var fi = value.GetType().GetField(value.ToString());

        if (fi == null) return attributeValue;
        var attributes = fi.GetCustomAttributes(typeof(T), false) as T[];

        if (attributes == null || attributes.Length <= 0) return attributeValue;
        var attribute = attributes[0] as IAttribute<TR>;

        if (attribute != null)
        {
            attributeValue = attribute.Value;
        }

        return attributeValue;
    }
}

Here, I would like to define my custom attributes such as (FormNameAttribute, FormCaptionAttribute, etc.,) from database table (columns) when we create dynamic enum at run-time. Is it possible to do this?





Aucun commentaire:

Enregistrer un commentaire