从类型的成员获取属性的通用方法

时间:2018-10-02 17:39:11

标签: c# .net generics reflection attributes

我创建了一个方便的方法,该方法使用泛型来检索应用于类型的属性:

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

这仅适用于类型的属性。即如果我具有此属性:

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

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

我可以这样做:

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

然后这个:

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

但是如果我有一个这样的属性(不是有意义,只是出于演示目的):

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

我希望能够使用类似的方法。有没有一种方法可以使用泛型来促进从 any System.Reflection.MemberInfo中获取属性,而不仅仅是System.Type

1 个答案:

答案 0 :(得分:2)

您可以使用val it = [4,3,2,1] : int list 指定要从中获取属性的成员。这是一个示例:

f