c#反射检查属性

时间:2012-09-07 08:47:06

标签: c# mongodb serialization reflection bson

我想检查一个特定的运行时类型是否包含具有某个属性的属性,如下所示:

    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 个答案:

答案 0 :(得分:1)

变化:

 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()返回属性上的属性对象列表。您需要遍历它们并检查它们的任何TYPES是否属于BsonIgnoreAttribute。

答案 1 :(得分:0)

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