【发布时间】:2022-10-04 17:59:08
【问题描述】:
我正在使用以下代码:
public static List<T> ConvertToList1<T>(DataTable dt)
{
var columnNames = dt.Columns.Cast<DataColumn>()
.Select(c => c.ColumnName)
.ToList();
var properties = typeof(T).GetProperties();
return dt.AsEnumerable().Select(row =>
{
T objT1 = Activator.CreateInstance<T>();
foreach (var pro in properties)
{
if (columnNames.Contains(pro.Name))
{
PropertyInfo? pI = objT.GetType().GetProperty(pro.Name);
pro.SetValue(objT, row[pro.Name] == DBNull.Value ? null : Convert.ChangeType(row[pro.Name], pI.PropertyType));
}
}
return objT1;
}).ToList();
}
但是对于具有空值的十进制字段,我收到错误消息。
从 'System.Decimal' 到 'System.Nullable`1[[System.Decimal, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral 的无效转换
public class SampleModel
{
public Guid Id { get; set; }
public Guid ProjectId { get; set; }
public string? Code { get; set; } = null!;
public string? Description { get; set; }
public decimal? Quantity1 { get; set; }
public decimal? Quantity2 { get; set; }
}
谁能建议如何解决这个问题?
【问题讨论】:
-
这回答了你的问题了吗? Set property Nullable<> by reflection