[深入學習C#]利用反射給物件賦值
阿新 • • 發佈:2019-01-26
C#中利用反射能夠獲取物件的屬性資訊,也可以利用反射給物件賦值。
我們如果想利用凡是給一個物件屬性賦值可以通過PropertyInfo.SetValue()方式進行賦值,但要注意值的型別要與屬性保持一致。
假設我們有如下一個結構:
struct Person
{
public string code{get; set;}
public string name{get; set;}
}
下面一段程式碼,展示瞭如何利用反射來給物件賦值:
Person p =new Person(){code="123456", name="Jay" };
Person item=new Person();
PropertyInfo[] props=p.GetType().GetProperties();
props.ToList().ForEach(
pi=>
{
if (!pi.PropertyType.IsGenericType)
{
if (pi.GetValue(p) != null)
{
pi.SetValue(item , Convert.ChangeType(pi.GetValue(p), pi.PropertyType));
}
}
else
{
Type genericTypeDefinition = pi.PropertyType.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
if (pi.GetValue(p) != null)
{
pi.SetValue(item, Convert.ChangeType(pi.GetValue(p), Nullable.GetUnderlyingType(pi.PropertyType)));
}
}
});
pi.SetValue(item, Convert.ChangeType(pi.GetValue(p), pi.PropertyType))
pi.SetValue(item, Convert.ChangeType(pi.GetValue(p), Nullable.GetUnderlyingType(pi.PropertyType)))
這兩行程式碼,分別是給非泛型屬性賦值和給泛型屬性賦值。