开发者

Get by reflection properties of class attribute

开发者 https://www.devze.com 2023-03-30 14:11 出处:网络
I find classes inherit from interface : var baseType = typeof(ICustomSerialization); Assembly assembly = baseType.Assembly;

I find classes inherit from interface :

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

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

If class have attribute and parameter Name:

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

It is a way to get by ref开发者_Python百科lection Name property of this attribute?


Try this

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

And the usage

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();
0

精彩评论

暂无评论...
验证码 换一张
取 消