Daniel Robinson
Daniel Robinson

Reputation: 14858

c# reflection checking for attributes

I want to check whether a particular runtime type contains a property with a certain attribute like this:

    public void Audit(MongoStorableObject oldVersion, MongoStorableObject newVersion)
    {
        if(oldVersion.GetType() != newVersion.GetType())
        {
            throw new ArgumentException("Can't Audit versions of different Types");
        }
        foreach(var i in oldVersion.GetType().GetProperties())
        {
            //The statement in here is not valid, how can I achieve look up of a particular attribute
            if (i.GetCustomAttributes().Contains<Attribute>(MongoDB.Bson.Serialization.Attributes.BsonIgnoreAttribute)) continue;
            //else do some actual auditing work
        }
    }

But the statement is not valid, Can you tell me how to achieve lookup of a particular attribute on a property like this? Thanks,

Update:

I've found this which doesn't make intellisense complain:

if (i.GetCustomAttributes((new MongoDB.Bson.Serialization.Attributes.BsonIgnoreAttribute()).GetType(),false).Length > 0) continue;

But I'm still not certain this will do what I want it too.

Upvotes: 0

Views: 420

Answers (2)

armen.shimoon
armen.shimoon

Reputation: 6401

Change:

 if (i.GetCustomAttributes().Contains<Attribute>(MongoDB.Bson.Serialization.Attributes.BsonIgnoreAttribute)) continue;

to

if (i.GetCustomAttributes().Any(x=> x is MongoDB.Bson.Serialization.Attributes.BsonIgnoreAttribute)) continue; 

Revised:

public void Audit(MongoStorableObject oldVersion, MongoStorableObject newVersion)
    {
        if(oldVersion.GetType() != newVersion.GetType())
        {
            throw new ArgumentException("Can't Audit versions of different Types");
        }
        foreach(var i in oldVersion.GetType().GetProperties())
        {
            //The statement in here is not valid, how can I achieve look up of a particular attribute
             if (i.GetCustomAttributes().Any(x=> x is MongoDB.Bson.Serialization.Attributes.BsonIgnoreAttribute)) continue;
            //else do some actual auditing work
        }
    }

To clarify:

GetCustomAttributes() returns a list of attribute objects on the property. You need to iterate through them and check whether any of their TYPES are of BsonIgnoreAttribute.

Upvotes: 1

opewix
opewix

Reputation: 5083

private static void PrintAuthorInfo(System.Type t)
{
    System.Console.WriteLine("Author information for {0}", t);

    // Using reflection.
    System.Attribute[] attrs = System.Attribute.GetCustomAttributes(t);  // Reflection. 

    // Displaying output. 
    foreach (System.Attribute attr in attrs)
    {
        if (attr is Author)
        {
            Author a = (Author)attr;
            System.Console.WriteLine("   {0}, version {1:f}", a.GetName(), a.version);
        }
    }
}

http://msdn.microsoft.com/en-us/library/z919e8tw.aspx

Upvotes: 0

Related Questions