属性

配置

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property,AllowMultiple=true,Inherited=false)]
    public class fieldattr : System.Attribute { 
        
        public fieldattr(string name){
            this.Name = name;
        }
 
        public string Name{protected set;get;}
 
    }
 
    public class Model {
        [fieldattr("自增ID")]
        public   int Id { get; set; }
        [fieldattr("名称")]
        public  string names  { get; set; }
        [fieldattr("创建日期")]
        public DateTime CreateDate { get; set; }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
             var m = new Model()
            {
                Id = 1,
                names = "ChenJ",
                CreateDate = DateTime.Now
            };
 
            Type type = typeof(Model);
            var p=type.GetProperties();
 
            DataTable dt = new DataTable();
            foreach (var field in p)
            {
                var fieldattrs = field.GetCustomAttributes(false);//获取属性集合
                foreach (var a in fieldattrs)
                {
                    if (a is fieldattr)
                    {
                        Console.WriteLine((a as fieldattr).Name);
                        var col = new DataColumn((a as fieldattr).Name);
                        dt.Columns.Add(col);
                    }
 
                }
            }
 
               
           
            
 
            Console.ReadKey();
 
        }
posted @ 2018-08-09 14:40  威尔逊  阅读(195)  评论(0)    收藏  举报