C# отражение проверки атрибутов

Я хочу проверить, содержит ли конкретный тип среды выполнения свойство с определенным атрибутом, например так:

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

Но утверждение недействительно. Можете ли вы сказать мне, как добиться поиска определенного атрибута для свойства, подобного этому? Спасибо,

Обновить:

Я нашел это, которое не заставляет intellisense жаловаться:

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

Но я все еще не уверен, что это будет делать то, что я тоже хочу.

2 ответа

Решение

Изменить:

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

в

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

После доработки:

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

Чтобы уточнить:

GetCustomAttributes () возвращает список объектов атрибута для свойства. Вам нужно перебрать их и проверить, имеют ли какие-либо из их ТИПОВ атрибут BsonIgnoreAttribute.

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

Другие вопросы по тегам