Reflection c# WPF Observablecollection

Asked

Viewed 27 times

0

I have a problem, when creating an Observablecollection I do so:

ObservableCollection<MinhaClasse> Lista = new ObservableCollection<MinhaClasse>();

So far so good. My problem is, through Reflection I read all fields, and if it is a List as in the above case, I need to create a new Observablecollection

my question is: how will I do it? how will I fill that my class via Reflection if I don’t know which class is?

 ObservableCollection<????> ListaGeneric = new ObservableCollection<???>();

1 answer

0


Perhaps you should elaborate a little more on your question. Let us know, for example, how you are accessing the collection. But anyway, it follows an example of how to create the instance of the Observablecollection through a generic type:

        var tipo = typeof(string);

        var tipoColecao = typeof(ObservableCollection<>).MakeGenericType(tipo);

        var novaLista = Activator.CreateInstance(tipoColecao); 

Obs.: The variable newcomer will be an Object type. Therefore, you cannot call newList.Add directly. You can cast for an Ilist if you call Add "manually";

        var novaLista = (IList) Activator.CreateInstance(tipoColecao);
        novaLista.Add("Meu texto legal");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.