我有幾個包含各種屬性的類。這裏有一個例子:如何獲取嵌入在自定義屬性中的類型?
[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);