C# 將object對象轉換為實體對象.代碼如下: 調用時: 是不是很簡單? ...
C# 將object對象轉換為實體對象.代碼如下:
/// <summary> /// 將object對象轉換為實體對象 /// </summary> /// <typeparam name="T">實體對象類名</typeparam> /// <param name="asObject">object對象</param> /// <returns></returns> private T ConvertObject<T>(object asObject) where T : new() { //創建實體對象實例 var t = Activator.CreateInstance<T>(); if (asObject != null) { Type type = asObject.GetType(); //遍歷實體對象屬性 foreach (var info in typeof(T).GetProperties()) { object obj = null; //取得object對象中此屬性的值 var val = type.GetProperty(info.Name)?.GetValue(asObject) if (val != null) { //非泛型 if (!info.PropertyType.IsGenericType) obj = Convert.ChangeType(val, info.PropertyType) else//泛型Nullable<> { Type genericTypeDefinition = info.PropertyType.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { obj = Convert.ChangeType(val, Nullable.GetUnderlyingType(info.PropertyType)); } } info.SetValue(t, obj, null); } } } return t; }
調用時:
/// <summary> /// test /// </summary> public void test() { var obj = new { id=1,name="張三",sex=1,age=22 }; //轉換 var userModel = ConvertObject<user>(obj); } /// <summary> /// 用戶 /// </summary> public class user { /// <summary> /// 編號 /// </summary> public int id { set; get; } /// <summary> /// 姓名 /// </summary> public string name { set; get; } /// <summary> /// 性別 /// </summary> public int sex { set; get; } /// <summary> /// 年齡 /// </summary> public int age { set; get; } }
是不是很簡單?