c#遍历并判断实体或类的成员属性

c#的Attribute有些类似java中的annotation,可以方便地在类成员中做修饰/限制作用。

Demo:

class ss {
    public stat BsonDocument Iterator(object obj){
        MyAttr currAttr = null;// 自定义注解类
        Type type = obj.GetType();// obj为传入的对象参数
        //获取类名
        String className = type.Name;
        //获取所有公有属性
        PropertyInfo[] info = type.GetProperties();
        // 遍历所有属性
        foreach (PropertyInfo var in info)
        {
            //判断是否含有MongoDB相关注解(一个属性可以包含多个注解)
            Object[] attrs = var.GetCustomAttributes(false);// 取得属性的特性标签,false表示不获取因为继承而得到的标签
            if (attrs.Length > 0)
            {
                foreach(Object attr in attrs)// 遍历该属性的所有注解
                {
                   if ((currAttr = attr as MyAttr) != null && currAttr.AddToDB)// 判断是否有属性修饰,并判断属性值
                    {
                        bson.Add(var.Name, var.GetValue(obj,null).ToString());
                    }
                }
            }
        }
    }
}

// 自定义注解类
public class MyAttr : Attribute
{
    public bool AddToDB;
}
    
//实体类定义:

class Entity
{
    [MyAttr(AddToDB=true)]
    public string aa{get; set;}
    
    public string bb{get; set;}
    
}
View Code
原文地址:https://www.cnblogs.com/lbhqq/p/5529672.html