jeudi 1 novembre 2018

Casting reflected property to ObservableCollection

I have a C# program in which I get values of properties in a class by means of reflection. Some of these properties are ObservableCollections. I'm using those specifically because I want to access the CollectionChanged event.

Here's how I get the property:

var o = propertyInfo.GetValue(this, null);

Now I know (from other conditions in the code) that this is an ObservableCollection. But I can't just use 'o.CollectionChanged' because the compiler doesn't see it that way.

What I figured I should do was to cast 'o' to an ObservableCollection. Something like this perhaps:

(o as ObservableCollection<>).CollectionChanged...

But unfortunately that won't work. I get an error between the angular brackets that says 'type expected'.

Can I get the type within o? Sure, I can use GetGenericArguments, which returns the type of the items in the ObservableCollection. But the problem is, I can't put that type between the angular brackets when casting - it just won't allow it.

How can I do this?

I am aware there is another similar question to this, but it does not address my question and the solutions do not answer my question, as far as I can see. I also think it would be difficult to ask more about that, since the question is almost five years old.





Aucun commentaire:

Enregistrer un commentaire