【发布时间】:2011-09-30 21:50:36
【问题描述】:
【问题讨论】:
-
你能更精确一点吗?您想创建一个新的数据表,其中包含 T 实例的属性/字段的快照,还是想要某种代理对象通过类似数据表的形状来表示您的 T 实例?
-
你为什么要这样做呢?可能有更好的方法。
标签: .net
【问题讨论】:
标签: .net
我使用以下扩展方法从 IEnumerable 生成数据库。 希望这会有所帮助。
public static DataTable ToDataTable<TSource>(this IEnumerable<TSource> source)
{
var tb = new DataTable(typeof (TSource).Name);
var props = typeof (TSource).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var prop in props)
{
Type t = GetCoreType(prop.PropertyType);
tb.Columns.Add(prop.Name, t);
}
foreach (var item in source)
{
var values = new object[props.Length];
for (var i = 0; i < props.Length; i++)
{
values[i] = props[i].GetValue(item, null);
}
tb.Rows.Add(values);
}
return tb;
}
public static Type GetCoreType(Type t)
{
return t != null && IsNullable(t)
? (!t.IsValueType ? t : Nullable.GetUnderlyingType(t)) : t;
}
public static bool IsNullable(Type t)
{
return !t.IsValueType || (t.IsGenericType
&& t.GetGenericTypeDefinition() == typeof(Nullable<>));
}
【讨论】: