2017-09-06 57 views
0

我有几个包含各种属性的类。这里有一个例子:如何获取嵌入在自定义属性中的类型?

[XmlInclude(typeof(AFReader))] 
[XmlInclude(typeof(SQLReader))] 
[XmlInclude(typeof(MySQLReader))] 
[Serializable] 
[DataContract] 
public class DataSource  
{ 
    ...      
} 

我需要能够通过这些属性来过滤和选择其BaseType的是,在这里它继承(DataSource在这种情况下)的类型。

所以最后,我想是这样的:

static private List<Type> AttributeFilter(IEnumerable<Attribute> attributes, Type baseType) 
    { 
     List<Type> filteredAttributes = new List<Type>(); 
     foreach (Attribute at in attributes) 
     { 

      // if (at.TypeId.GetType().BaseType == baseType) 
      //  filteredAttributes.Add(at.GetType()); 

      // if (at.GetType().BaseType == baseType) 
      //  filteredAttributes.Add(at.GetType()); 

     } 

     return filteredAttributes; 
    } 

与调用:

  Type test = typeof(DataSource); 

      IEnumerable<Attribute> customAttributes = test.GetCustomAttributes(); 
      List<Type> filteredAttributes = AttributeFilter(customAttributes, test); 

回答

1

首先,你要,我试过

List<Type> filteredAttributes = {typeof(AFReader), typeof(SQLReader), typeof(MySQLReader)}; 

//List<MemberInfo> .. would work as well 

事将您的属性限制为XmlIncludeAttribute。然后,您可以检查属性'Type属性。所以,你的函数如下所示:

static private List<Type> AttributeFilter(IEnumerable<XmlIncludeAttribute> attributes, Type baseType) 
{ 
    List<Type> filteredAttributes = new List<Type>(); 
    foreach (XmlIncludeAttribute at in attributes) 
    { 
     if (at.Type.BaseType == baseType) 
     { 
      filteredAttributes.Add(at.Type); 
     } 
    } 
    return filteredAttributes; 
} 

你可以这样调用:

IEnumerable<XmlIncludeAttribute> customAttributes = test.GetCustomAttributes().Where(x => x is XmlIncludeAttribute).Select(x => x as XmlIncludeAttribute); 
List<Type> filteredAttributes = AttributeFilter(customAttributes, test); 
1

您的代码看属性本身的Type通过调用GetType(),而不是Type简称由它的构造函数中的属性。尝试是这样的:

public static IEnumerable<Type> GetXmlIncludeTypes(Type type) { 
    foreach (var attr in Attribute.GetCustomAttributes(type)) { 
     if (attr is XmlIncludeAttribute) { 
      yield return ((XmlIncludeAttribute)attr).Type; 
     } 
    } 
} 

你会这样称呼它:

foreach (var t in GetXmlIncludeTypes(typeof(Foo))) { 
    //whatever logic you are looking for in the base types 
} 
相关问题