1. 程式人生 > >反射,自定義特性,對象復制

反射,自定義特性,對象復制

str pan 特性 復制 des sage tel write getprop

 [AttributeUsage(AttributeTargets.All)]
    public class VersionAttribute : Attribute
    {
        public string Name { get; set; }
        public string Date { get; set; }
        public string Describtion { get; set; }
    }

    [Version(Date = "2017 - 10 - 29", Describtion = "hello world", Name = "
wjire")] public class MyCode { [Version(Name = "GId")] public int Id { get; set; } [Version(Name = "GName")] public string Name { get; set; }

     public int Age { get; set; } }
public class GCode { public string GWjire { get; set; }
public int GId { get; set; } public string GName { get; set; } } public class Code { public int Id { get; set; } public string Name { get; set; } }

            var customAttr = (VersionAttribute)Attribute.GetCustomAttribute(typeof(MyCode), typeof(VersionAttribute));
            
string name = customAttr.Name; string date = customAttr.Date; string desc = customAttr.Describtion; Console.WriteLine($"name={name},date={date},desc={desc}");

屬性名稱相同的兩個類之間的復制

            MyCode myCode = new MyCode()
            {
                Name = "refuge",
                Id = 1
            };
            Code code = new Code();
            var myCodePro = typeof(MyCode).GetProperties();
            var codePro = typeof(Code).GetProperties();
            foreach (var mp in myCodePro)
            {
                foreach (var p in codePro)
                {
                    if (p.Name == mp.Name)
                    {
                        p.SetValue(code, mp.GetValue(myCode));
                        break;
                    }
                }
            }

            Console.WriteLine($"code.Name={code.Name}");
            Console.WriteLine($"code.Id={code.Id}");

屬性名稱不相同的兩個類之間的復制

            MyCode myCode = new MyCode()
            {
                Name = "refuge",
                Id = 1
            };
            GCode gCode = new GCode();
            var myCodePro = typeof(MyCode).GetProperties();
            var gCodePro = typeof(GCode).GetProperties();
            foreach (var mp in myCodePro)
            {
                var c = (VersionAttribute)Attribute.GetCustomAttribute(mp, typeof(VersionAttribute));

                //MyCode類的 Age 屬性沒有特性,所以這裏要加判斷,不然會報異常
                string name = c == null ? string.Empty : c.Name;

                foreach (var gp in gCodePro)
                {
                    if (gp.Name == name)
                    {
                        gp.SetValue(gCode, mp.GetValue(myCode));
                        break;
                    }
                }
            }

反射,自定義特性,對象復制