mardi 2 octobre 2018

Generic method to get an attribute from a member of a type

I created a convenience method that uses generics to retrieve an attribute applied to a type:

/// <summary>
/// Return an attribute from the provided type if it exists on that type.
/// </summary>
/// <typeparam name="T">The type whose attribute <typeparamref name="TAttType"/> 
/// will be returned if it exists on that type.</typeparam>
/// <typeparam name="TAttType">The type of attribute that will be retrieved
/// on <typeparamref name="T"/> if it exists.</typeparam>
/// <returns>Return the attribute with type <typeparamref name="TAttType"/>, 
/// if it exists, from target type <typeparamref name="T"/> or else
/// return null.</returns>
public static TAttType GetAttribute<T, TAttType>() where TAttType:Attribute 
    => (TAttType) typeof(T).GetCustomAttribute(typeof(TAttType), false);

This only works for attributes on types though. I.e. if I have this attribute:

public class VehicleAttribute : Attribute
{
    public string Color { get; }
    public int NumWheels { get; }

    public VehicleAttribute(string color, int numWheels)
    {
        Color = color;
        NumWheels = numWheels;
    }
}

I can do this:

[Vehicle("Yellow", 6)]
public class Bus { }

And then this:

var att = ReflectionTools.GetAttribute<Bus, VehicleAttribute>();

But if I have a property like this (not that it makes sense, but just for demo purposes):

[Vehicle("Blue", 5)]
public string Name { get; set; }

I want to be able to use a similar approach. Is there a way I can use generics to facilitate the retrieval of an attribute from any System.Reflection.MemberInfo, not just System.Type?





Aucun commentaire:

Enregistrer un commentaire