首页 > 代码库 > .NET通过字典给类赋值

.NET通过字典给类赋值

技术分享
 1 /// <summary> 2         ///  3         /// </summary> 4         /// <typeparam name="T"></typeparam> 5         /// <param name="origin">源数据</param> 6         /// <param name="target">对象数据</param> 7         /// <param name="dict">变量名对应字典</param> 8         public static void CopyTo<T>(this object origin, T target,Dictionary<string,string> dict)where T :class,new() 9         {10             PropertyInfo[] props = target.GetType().GetProperties();11 12             foreach (PropertyInfo info in props)13             {14                 var variable = dict.FirstOrDefault(m => m.Value =http://www.mamicode.com/= info.Name);15                 if (variable.Key!=null)16                 {17                     string variableName = variable.Key;18                     string chineseName = variable.Value;19                     var propertyValue =http://www.mamicode.com/20                         origin.GetType()21                             .GetProperty(variableName)22                             .GetValue(origin, null);23                     if (propertyValue != null)24                     {25                         if (propertyValue.GetType().IsClass)26                         {27 28                         }29                         target.GetType()30                             .InvokeMember(chineseName, BindingFlags.SetProperty, null, target,31                                 new object[] { propertyValue });32                     }33                 }34             }35         }
View Code

 

.NET通过字典给类赋值