btm*_*ach 0 c# generics reflection
我一直在研究这种方法一段时间,并试图弄清楚它是如何工作的.这显然适用于返回完美的对象列表.但我目前无法弄清楚的是我将如何检索单个对象,例如"Employee e"而不是"List"?
public static List<T> DataTableToList<T>(this DataTable table) where T : class, new()
{
try
{
List<T> list = new List<T>();
foreach (var row in table.AsEnumerable())
{
T obj = new T();
foreach (var prop in obj.GetType().GetProperties())
{
try
{
PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name);
propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null);
}
catch
{
continue;
}
}
list.Add(obj);
}
return list;
}
catch
{
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
打电话吧
var employee = table.DataTableToList<Employee>().FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)
或者(如果您DataTable非常大),您可能希望IEnumerable<T>使用yield关键字修改您的扩展方法以返回:
public static IEnumerable<T> DataTableToList<T>(this DataTable table) where T : class, new()
{
try
{
foreach (var row in table.AsEnumerable())
{
T obj = new T();
foreach (var prop in obj.GetType().GetProperties())
{
try
{
PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name);
propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null);
}
catch
{
continue;
}
}
yield return obj;
}
}
catch
{
yield break;
}
}
Run Code Online (Sandbox Code Playgroud)
这样做的好处是该方法只会根据需要转换表的多行.
| 归档时间: |
|
| 查看次数: |
78 次 |
| 最近记录: |