如何获取嵌入在自定义属性中的类型?

时间:2017-09-06 01:53:30

标签: c# reflection

我有几个包含各种属性的类。这是一个例子:

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

我需要能够过滤这些属性,并选择BaseType所继承的类型(在这种情况下为DataSource)。

所以最后我想要这样的事情:

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

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

我尝试过的事情:

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

2 个答案:

答案 0 :(得分:1)

首先,您希望将属性限制为仅XmlIncludeAttribute的属性。然后,您可以检查属性&#39; 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 :(得分: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
}