首先,我是新来的反思。我创建的类:使用反射填充自定义类属性
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; }
}
现在我试图开发将使用一些商业逻辑填充所有属性的方法(如果为空则空字符串等)通过反射,并返回的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
。 缺什么? 谢谢。
我在代码审查网站上提出了同样的问题。我有一些非常好的评论意见来做到这一点。你可以在这里检查问题http://codereview.stackexchange.com/questions/102289/setting-the-value-of-properties-via-reflection – Sandeep