1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- /*-------------------------------------------------------------------------
- * 功能描述:ReflectTest
- * 作者:xulisong
- * 创建时间: 2019/3/12 15:05:10
- * 版本号:v1.0
- * -------------------------------------------------------------------------*/
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Reflection;
- using System.Text;
- using System.Threading.Tasks;
- using FWindSoft.Tools;
- namespace Test.CalcTrans
- {
- public static class ReflectTest
- {
- public static T Create<T>(Dictionary<string,string> dic)
- {
- T t = Activator.CreateInstance<T>();
- PropertyInfo[] properties = t.GetType().GetProperties();
- for (int i = 0; i < properties.Length; i++)
- {
- PropertyInfo propertyInfo = properties[i];
- try
- {
- var value = dic[propertyInfo.Name];
- propertyInfo.SetValue(t, TypeUtil.ChangeType(value, propertyInfo.PropertyType) ?? "", null);
- }
- catch(Exception ex)
- {
- }
- }
- return t;
- }
- public static void Test()
- {
- Dictionary<string, string> value = new Dictionary<string, string>();
- value["IntValue"] = "15";
- value["BoolValue"] = "true";
- value["StringValue"] = "13";
- value["DoubleValue"] = "15.18";
- value["EnumValue"] = "Hello";
- var item = Create<ReflectItem>(value);
- }
- }
- public class ReflectItem
- {
- public int IntValue { get; set; }
- public bool BoolValue { get; set; }
- public string StringValue { get; set; }
- public double DoubleValue { get; set; }
- public ReflectEnum EnumValue { get; set; }
- }
- public enum ReflectEnum
- {
- None,
- Hello,
- }
- }
|