dimanche 8 septembre 2019

Dealing with an invalid cast - IList to List

I'm using C# 4.0 and I have a problem with reflection and casting. I've read through a few threads on StackOverflow and none that I've tried so far have given a solution that works for me.

The problem: I have a class, Character, which is derived from another class, called GenericDataObjectWithUniqueID. I have a list of Characters (as in, type List) and I want to get them through reflection as a

List<GenericDataObjectWithUniqueID>. 

So far I use the following:

(IList)p.GetValue(context, null);

This will get me the list in question, no problem, but as an IList. What I want, as I said, is List.

So I've tried this:

(List<GenericDataObjectWithUniqueID>)p.GetValue(context, null);

Now I know, for purposes of testing, that the list is Characters (List(Character)) and Character derives from GenericDataObjectWithUniqueID.

When I run the line above, I get the following:

Unable to cast object of type 'System.Collections.Generic.List1[GameSystem.DataModel.Character]' to type 'System.Collections.Generic.List1[WPF_MVVM_GenericBaseDLL.Data_Objects.GenericDataObjectWithUniqueID]'.

I must be going mad because I've checked about ten times. Character derives from GenericDataObjectWithUniqueID.

I have tried this too:

IList propertyList = (IList)p.GetValue(context, null);
List<GenericDataObjectWithUniqueID> newList = new List<GenericDataObjectWithUniqueID>(propertyList);

This tells me that "Argument 1: cannot convert from 'System.Collections.IList' to 'System.Collections.Generic.IEnumerable'"

I also tried this:

IList propertyList = (IList)p.GetValue(context, null);
List<GenericDataObjectWithUniqueID> newList = propertyList as List<GenericDataObjectWithUniqueID>;

I don't get an error here, but 'newList' is null.

These are the suggestions from this thread, but no luck so far.

I hope I'm just missing something simple. And please, no, I can't just go ahead and use IList. I have tried that too, but I have code further along that requires the use of

List<GenericDataObjectWithUniqueID>.





Aucun commentaire:

Enregistrer un commentaire