2017-09-06 59 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 
} 
相關問題