mardi 5 septembre 2017

How to get the type embedded within a custom attribute?

I have several classes that contain various attributes. Here is one example:

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

I need to be able to filter through these attributes and select the types whose BaseType is that in which it inherits (DataSource in this case).

So in the end I would like something like this:

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

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

Things that I've tried:

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

Invoked with:

            Type test = typeof(DataSource);

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





Aucun commentaire:

Enregistrer un commentaire