Ajuda Reflection
Bom dia senhores.
Possuo 3 tipos de objetos armazenados em uma lista e quero coloca-los em uma datatable.
Porem, ao tentar usar o typeof (T) o meu codigo nao identifica o tipo do objeto. Se trocar T por algum tipo de objeto dentro da lista, ele reconhece.
Como faço para reconhecer o tipo do objeto em tempo de execução ??
Possuo 3 tipos de objetos armazenados em uma lista e quero coloca-los em uma datatable.
Porem, ao tentar usar o typeof (T) o meu codigo nao identifica o tipo do objeto. Se trocar T por algum tipo de objeto dentro da lista, ele reconhece.
Como faço para reconhecer o tipo do objeto em tempo de execução ??
public static DataTable ListToDataTable<T>(List<T> list) { DataTable dt = new DataTable(); foreach (PropertyInfo info in typeof(T).GetProperties()) { Type tipo = info.PropertyType; if (tipo.IsGenericType && tipo.GetGenericTypeDefinition() == typeof(Nullable)) tipo = Nullable.GetUnderlyingType(tipo); dt.Columns.Add(new DataColumn(info.Name, tipo)); } foreach (T t in list) { DataRow row = dt.NewRow(); foreach (PropertyInfo info in typeof(T).GetProperties()) { object value = info.GetValue(t, null); if (value != null) { row[info.Name] = value; } else { row[info.Name] = DBNull.Value; } } dt.Rows.Add(row); } return dt; }
Alex A.
Curtidas 0
Respostas
Alex A.
17/02/2012
public static DataTable ListToDataTable<T>(List<T> list)
{
DataTable dt = new DataTable();
foreach (PropertyInfo info in typeof(T).GetProperties())
{
Type tipo = info.PropertyType;
if (tipo.IsGenericType && tipo.GetGenericTypeDefinition() == typeof(Nullable))
tipo = Nullable.GetUnderlyingType(tipo);
dt.Columns.Add(new DataColumn(info.Name, tipo));
}
foreach (T t in list)
{
DataRow row = dt.NewRow();
foreach (PropertyInfo info in typeof(T).GetProperties())
{
object value = info.GetValue(t, null);
if (value != null)
{
row[info.Name] = value;
}
else
{
row[info.Name] = DBNull.Value;
}
}
dt.Rows.Add(row);
}
return dt;
}
{
DataTable dt = new DataTable();
foreach (PropertyInfo info in typeof(T).GetProperties())
{
Type tipo = info.PropertyType;
if (tipo.IsGenericType && tipo.GetGenericTypeDefinition() == typeof(Nullable))
tipo = Nullable.GetUnderlyingType(tipo);
dt.Columns.Add(new DataColumn(info.Name, tipo));
}
foreach (T t in list)
{
DataRow row = dt.NewRow();
foreach (PropertyInfo info in typeof(T).GetProperties())
{
object value = info.GetValue(t, null);
if (value != null)
{
row[info.Name] = value;
}
else
{
row[info.Name] = DBNull.Value;
}
}
dt.Rows.Add(row);
}
return dt;
}
GOSTEI 0