.net attribute 设置获取方法

来源:互联网 发布:怎么淘宝号 编辑:程序博客网 时间:2024/05/16 23:43
//备忘,忘性太大


namespace AttributeTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Person ps = new Person();
            ps.Id = 1;
            ps.Name = "23432";
            ps.Credit = 234324234M;
            Type t = ps.GetType();


            foreach (var item in t.GetProperties())
            {
                if (t.GetProperty(item.Name).GetValue(ps, null) != null)
                {
                    var a = Attribute.GetCustomAttributes(item);
                    foreach (var p in a)
                    {
                        if (p.GetType() == typeof(DBNameAttribute))
                        {
                            var b = (DBNameAttribute)p;
                            Console.WriteLine(b.DBName);
                        }
                    }
                }
            }


            Console.ReadLine();
        }
    }


    class Person
    {
        [DBName("ID")]
        public int? Id { get; set; }
        [DBName("Credit")]
        public decimal? Credit { get; set; }
        [DBName("PERSON_NAME")]
        public string Name { get; set; }
        public Person()
        {
            Id = null;
            Credit = null;
        }
    }
}
0 0
原创粉丝点击