【发布时间】:2015-12-14 12:19:01
【问题描述】:
首先,我是反射新手。我已经创建了类:
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 。
缺什么 ?
谢谢。
【问题讨论】:
-
我在代码审查网站上问过同样的问题。我得到了一些非常好的评论 cmets 来做到这一点。你可以在这里查看问题codereview.stackexchange.com/questions/102289/…
标签: c# reflection