c# 实体转换

318 阅读1分钟

c# 实体转换

使用特性进行实体转换

原理很简单,就是反射获取特性上需要转成的属性名,进行转换 比如 UserVM 中的 userName 转成 User中的username,由于属性名称不一致,需要添加特性进行标明,若属性名一直则直接进行转换。

自定义特性


// 一个自定义特性
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
public class MapperAttribute : Attribute
{
    public MapperAttribute(string Key)
    {
        this.Key = Key;
    }

    public string Key { get; set; }
}

反射解析特性处理实体

public static class MapperExtension
    {
        /// <summary>
        /// 实体转换
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="S"></typeparam>
        /// <param name="source"></param>
        /// <returns></returns>
        public static S EntityConvert<T, S>(this T source)
        {
            S target = Activator.CreateInstance<S>();
            var sType = source.GetType();
            var dType = typeof(S);
            foreach (PropertyInfo now in sType.GetProperties())
            {
                var mappers = now.GetCustomAttributes(typeof(MapperAttribute), false);
                // 没有特性,表示属性名一致
                if (mappers.Length == 0)
                {
                    var name = dType.GetProperty(now.Name);
                    if (name == null)
                        continue;
                    dType.GetProperty(now.Name).SetValue(target, now.GetValue(source));
                }
                else
                {
                    // 获取要转换成的属性名
                    MapperAttribute mapper = mappers[0] as MapperAttribute;
                    // 获取属性名对于的属性
                    var name = dType.GetProperty(mapper.Key);
                    if (name == null)
                        continue;
                    // 属性存在即赋值
                    dType.GetProperty(mapper.Key).SetValue(target, now.GetValue(source));
                }
            }
            return target;
        }

        /// <summary>
        /// 集合转换
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="S"></typeparam>
        /// <param name="sourceList"></param>
        /// <returns></returns>
        public static List<S> EntityConvert<T, S>(this 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;
        }
    }

案例

相关实体

internal class User
{
    // username => userName
    [Mapper("userName")]
    public string username { get; set; }

    [Mapper("passWord")]
    public string password { get; set; }
}

internal class UserVM
{
    // userName => username
    [Mapper("username")]
    public string userName { get; set; }

    [Mapper("password")]
    public string passWord { get; set; }
}

转换实例


private static void Main(string[] args)
{
    UserVM userVM = new UserVM
    {
        userName = "秀元",
        passWord = "123456"
    };
    User user = userVM.EntityConvert<UserVM, User>();
    List<User> users = new List<User>();
    users.Add(user);
    Console.WriteLine("username:{0},password:{1}", user.username, user.password);

    List<UserVM> userVMs = users.EntityConvert<User, UserVM>();

    foreach (var u in userVMs)
    {
        Console.WriteLine("userName:{0},passWord:{1}", u.userName, u.passWord);
    }
}



image.png