C# 反射获取属性类型及属性值,两个实体转换

一、两个实体数据转换

/// <summary>
        /// 为属性赋值
        /// </summary>
        /// <typeparam name="T">源单类</typeparam>
        /// <typeparam name="S">需要转换的实体类</typeparam>
        /// <param name="source"></param>
        /// <returns></returns>
        public static S EntityConvert<T, S>(T source)
        {
            S target = Activator.CreateInstance<S>();
            var sType = source.GetType();
            var dType = typeof(S);
            foreach (PropertyInfo now in sType.GetProperties())
            {
                var name = dType.GetProperty(now.Name);
                if (name == null)
                    continue;
                dType.GetProperty(now.Name).SetValue(target, now.GetValue(source));
            }
            return target;
        }
View Code

 二、两个集合之间的转换

public static List<S> EntityConvert<T, S>(List<T> sourceList)
        {
            List<S> list = new List<S>();
            IEnumerator<T> enumerator = sourceList.GetEnumerator();
            while (enumerator.MoveNext())
            {
                list.Add(EntityConvert<T, S>(enumerator.Current));
            }
            return list;
        }
View Code

三、获取属性的名称、属性类型、属性值

public class User
    {
        public int Id { get; set; }
        public string name { get; set; }
        public decimal money { get; set; }
        public string sex { get; set; }
        public string Email { get; set; }
        public DateTime birth { get; set; }
        public int State { get; set; }
    }
public void Test(){
    var user = new User
            {
                birth = DateTime.Now,
                Email = "[email protected]",
                Id = 1,
                money = 123,
                name = "张三",
                sex = "",
                State = 1
            };
            var type = user.GetType().GetProperties();
            foreach (var item in type)
            {
                Console.WriteLine($"属性名称:{item.Name},属性值:{ item.GetValue(user)},属性类型:{item.PropertyType.Name}");
            }
}
View Code

猜你喜欢

转载自www.cnblogs.com/mybk/p/9082883.html