C# 映射(Reflection) 基本用法

  • 6609
  • 0
  • C#
  • 2020-02-11

藉由GetType().GetProperties()可以取得Class所有的Property Name

藉由GetValue(data, null)可以取得Prorerty的Value

//GetType 可取出 System.Type 類型
Type t = class.GetType();

//GetProperties 可取出 class 的所有 Properties
PropertyInfo[] props = t.GetProperties(BindingFlags.Instance | BindingFlags.Public);

//可使用foreach遍歷整個props
foreach (var item in props)
{
	var key = item.key;
	var value = item.value;
}

//GetProperty 可藉由 property name 取得對應的 Property
Type t2 = class.GetType();
PropertyInfo pi = t2.GetProperty("property name");

//GetValue 取得 Property 的 value 值,此處的model為表示對該實體進行操作
pi.GetValue(model, null);

//SetValue 可 assign 資料給 Property
pi.SetValue(model, "new date");

參考

[C#]快速將弱型別的property轉成強型別的方式

[C#.NET] 使用反射(Reflection)對物件的結構進行操作 (一)

Reflection-使用反射執行方法的7種方式