vendredi 20 octobre 2017

Attribute contents extracion

I'm trying to simplify code for extracting data from property attribute.

Attribute:

[AttributeUsage(AttributeTargets.Property)]
class NameAttribute : Attribute
{
    public string Name { get; }

    public ColumnAttribute(string name)
    {
        Name = name;
    }
}

Attribute contents extraction code ( null-checks removed ):

public static string GetName<T>(string propName)
{
    var propertyInfo = typeof(T).GetProperty(propName);
    var nameAttribute = (NameAttribute)propertyInfo.GetCustomAttributes(typeof(NameAttribute)).FirstOrDefault();
    return nameAttribute.Name;
}

Sample class:

class TestClass
{
    [Column("SomeName")]
    public object NamedProperty { get; set; }
}

Call sample:

var name = GetName<TestClass>(nameof(TestClass.NamedProperty))

Is it any way to rewrite attribute contents extraction method to simplify/shorten its call. It's too inconvenient for me due to its length.

Something like CallerMemberNameAttribute would be great but i found nothing.





Aucun commentaire:

Enregistrer un commentaire