Example #1
0
        public object DeepClone()
        {
            UserInfo userInfo = new UserInfo()
            {
                UserId = this.UserId,
                UserName = this.UserName,
                Roles = new List<RoleInfo>()
            };

            foreach (var role in this.Roles)
            {
                RoleInfo newRole = new RoleInfo()
                {
                    RoleId = role.RoleId,
                    RoleName = role.RoleName,
                    Modules = new List<ModuleInfo>()
                };

                userInfo.Roles.Add(newRole);

                foreach (var module in role.Modules)
                {
                    newRole.Modules.Add(module);
                }
            }

            return userInfo;

        }
Example #2
0
        static void Main(string[] args)
        {

            UserInfo userInfo = new UserInfo()
            {
                UserId = 1001,
                UserName = "******",
                Roles = new List<RoleInfo>()
            };

            RoleInfo role1 = new RoleInfo()
            {
                RoleId = 2001,
                RoleName = "注册用户",
                Modules = new List<ModuleInfo>()
            };

            userInfo.Roles.Add(role1);

            ModuleInfo m1 = new ModuleInfo()
            {
                ModuleId = 3001,
                ModuleName = "查看个人信息"
            };

            ModuleInfo m2 = new ModuleInfo()
            {
                ModuleId = 3002,
                ModuleName = "发送私信"
            };

            role1.Modules.Add(m1);
            role1.Modules.Add(m2);

            //浅克隆
            //UserInfo userInfo2 = userInfo.Clone() as UserInfo;

            //深克隆
            UserInfo userInfo2 = userInfo.DeepClone() as UserInfo;

            userInfo2.UserName = "******";

            RoleInfo role2 = new RoleInfo()
            {
                RoleId = 2002,
                RoleName = "企业用户",
                Modules = new List<ModuleInfo>()
            };

            ModuleInfo m3 = new ModuleInfo()
            {
                ModuleId = 3003,
                ModuleName = "发布商品"
            };

            ModuleInfo m4 = new ModuleInfo()
            {
                ModuleId = 3004,
                ModuleName = "购买商品"
            };

            userInfo2.Roles.Where(a => a.RoleId == 2001).FirstOrDefault().Modules.Add(m4);


            role2.Modules.Add(m3);

            userInfo2.Roles.Add(role2);

            Console.ReadLine();



        }