我正在尝试将泛型集合(列表)转换为DataTable。我找到了以下代码来帮助我做到这一点:
// Sorry about indentation
public class CollectionHelper
{
private CollectionHelper()
{
}
// this is the method I have been using
public static DataTable ConvertTo<T>(IList<T> list)
{
DataTable table = CreateTable<T>();
Type entityType = typeof(T);
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);
foreach (T item in list)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
{
row[prop.Name] = prop.GetValue(item);
}
table.Rows.Add(row);
}
return table;
}
public static DataTable CreateTable<T>()
{
Type entityType = typeof(T);
DataTable table = new DataTable(entityType.Name);
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);
foreach (PropertyDescriptor prop in properties)
{
// HERE IS WHERE THE ERROR IS THROWN FOR NULLABLE TYPES
table.Columns.Add(prop.Name, prop.PropertyType);
}
return table;
}
}
我的问题是,当我将MySimpleClass的一个属性更改为可以为空的类型时,我得到了以下错误:
DataSet does not support System.Nullable<>.
如何在我的类中使用可以为空的属性/字段来实现这一点?
发布于 2009-03-31 14:33:21
然后,您可能需要使用Nullable.GetUnderlyingType
将它们提升到不可为空的形式,并可能将一些null
值更改为DbNull.Value
...
将分配更改为:
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
在添加要添加的列时:
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(
prop.PropertyType) ?? prop.PropertyType);
而且它是有效的。(??
是空合并运算符;如果第一个操作数非空,它将使用第一个操作数,否则将计算并使用第二个操作数)
发布于 2009-03-31 14:34:26
井。由于DataSet不支持可以为空的类型,因此您必须检查该属性是否为泛型类型,获取该类型的泛型定义,然后使用Nullable.GetUnderlyingType
获取参数(即实际类型)。如果值为空,只需在DataSet中使用DBNull.Value
即可。
发布于 2009-03-31 14:34:29
如果给定prop.PropertyType
的Nullable.GetUnderlyingType()
返回非空值,则使用该值作为列的类型。否则,使用prop.PropertyType
本身。
https://stackoverflow.com/questions/701223
复制相似问题