码迷,mamicode.com
首页 > Web开发 > 详细

.NET通过字典给类赋值

时间:2016-09-03 16:48:52      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:

技术分享
 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 == info.Name);
15                 if (variable.Key!=null)
16                 {
17                     string variableName = variable.Key;
18                     string chineseName = variable.Value;
19                     var propertyValue =
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通过字典给类赋值

标签:

原文地址:http://www.cnblogs.com/fb208/p/5837334.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!