C# attribute特性实例

   public class AttributeInstance
    {
        public void T TestAttr()
        {
            LSize lSize = new LSize
            {
                height = "234",
                width = "678"
            };

            //根据USize属性Height,Width对应的特性名称获取LSize的属性值,赋值给USize属性
            USize uSize = lSize.ToCustomEntity<USize>();

           //打印出结果
            System.Diagnostics.Debug.WriteLine(uSize.Width);
            System.Diagnostics.Debug.WriteLine(uSize.Height);
        }

    }

        public class USize
        {
            [ColumnName("width")]
            public string Width { get; set; }
            [ColumnName("height")]
            public string Height { get; set; }
        }


        public class LSize
        {
            public string width { get; set; }
            public string height { get; set; }
        }
    }


//obejct扩展方法

 public static class ObjectHelper

    {

      //object扩展方法,更具对象的属性的特性名称,读取对象的属性值,并赋值

        public static T ToCustomEntity<T>(this object entity)
        {
            T t = Activator.CreateInstance<T>();
            if (entity == null)
                return t;
            string columnName = "";
            foreach (PropertyInfo p in typeof(T).GetProperties())
            {
                object[] baseAttributes = p.GetCustomAttributes(typeof(BaseAttribute), false);
                if (baseAttributes != null && baseAttributes.Length > 0)
                {
                    columnName = ((BaseAttribute)baseAttributes[0]).Name;
                    p.SetValue(t, entity.GetPropertyValue(columnName), null);
                }
            }
            return t;
        }
        public static object GetPropertyValue(this object entity, String property)
        {
            Type info = entity.GetType();
            var props = info.GetProperty(property);
            object value = props.GetValue(entity, null);           
            return value;
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值