获取类属性的反射属性

时间:2011-08-25 14:48:56

标签: reflection c#-4.0 attributes

我发现类继承自interface:

  var baseType = typeof(ICustomSerialization);
  Assembly assembly = baseType.Assembly;

   var subClass = assembly.GetTypes().Where(t => t.IsSubclassOf(baseType) );

如果class有属性和参数Name:

    [CustomAttribute(Name="Soap")]
    class CustomSoapSerializer : ICustomSerialization

这是通过反射获取此属性的Name属性的方法吗?

1 个答案:

答案 0 :(得分:3)

试试这个

public static class CustomAttributeProviderExtensions
{
    public static TAttribute[] GetCustomAttributes<TAttribute>(this ICustomAttributeProvider self)
        where TAttribute:Attribute
    {
        return (TAttribute[])self.GetCustomAttributes(typeof(TAttribute), true);
    }
}

用法

var baseType = typeof(ICustomSerialization);
Assembly assembly = baseType.Assembly;

var subClass = assembly.GetTypes().Where(t => baseType.IsAssignableFrom(t))
    .Where(t=>t.GetCustomAttributes<CustomAttribute>().Any(x=>x.Name == "Soap"))
    .ToList();