[英]Populating custom class properties using Reflection
首先,我是新手。 我創建了課程:
using System.Reflection;
public class EmployeeInfo
{
public string EmployeeName { get; set; }
public string PhoneNumber { get; set; }
public string Office { get; set; }
public string Department { get; set; }
public string Position { get; set; }
public string PhoneType { get; set; }
public bool IsPublic { get; set; }
}
現在,我正在嘗試開發一種方法,該方法將通過反射使用一些業務邏輯(如果為null,然后為空字符串等)填充所有屬性,並返回EmployeeInfo
列表。 我認為它應該看起來像這樣:
public List<Models.EmployeeInfo> GetEmployeeInfo(SPListItemCollection splic)
{
var listEmployeeInfo = new List<Models.EmployeeInfo>();
var propertyNames = new List<string>() {"EmployeeName","Position","Office","IsPublic"};
foreach (SPListItem item in splic)
{
var employeeInfo = new Models.EmployeeInfo();
foreach (var propertyName in propertyNames)
{
string newData = "";
if (item[propertyName] != null)
{
newData = item[propertyName].ToString();
}
employeeInfo.GetProperty(propertyName).SetValue(employeeInfo, newData, null);
}
listEmployeeInfo.Add(employeeInfo);
}
return listEmployeeInfo;
}
但是我不能在這一行調用GetProperty
或SetValue
擴展方法:
employeeInfo.GetProperty(propertyName).SetValue(employeeInfo, newData, null);
錯誤消息說我的Models.EmployeeInfo
類不包含GetProperty
定義,也沒有擴展方法GetProperty
。 缺什么 ? 謝謝 。
GetProperty是Type類上的方法。
employeeInfo.GetType().GetProperty(propertyName).SetValue(employeeInfo, newData, null);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.