Ajuda Reflection

17/02/2012

0

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 ??


        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.

Alex A.

Responder

Posts

17/02/2012

Alex A.

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;
}
Responder

Que tal ter acesso a um e-book gratuito que vai te ajudar muito nesse momento decisivo?

Ver ebook

Recomendado pra quem ainda não iniciou o estudos.

Eu quero
Ver ebook

Recomendado para quem está passando por dificuldades nessa etapa inicial

Eu quero

Utilizamos cookies para fornecer uma melhor experiência para nossos usuários, consulte nossa política de privacidade.

Aceitar