.NET通过字典给类赋值
Posted FB208
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了.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 == 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 }
以上是关于.NET通过字典给类赋值的主要内容,如果未能解决你的问题,请参考以下文章