samedi 10 mars 2018

foreach for dynamic type C# - dynamic casting? reflection?

I defined various classes like this: public class Subclass : BaseObject, IObject, IObject { ... }

BaseObject<T> contains all the functionality I need. IObject<T> allows it to be access between projects. IObject allows collections to be created: List<IObject>.

BaseObject<T> and IObject<T> have a property T Value;

So I have

public class BaseObject<T>  // T is double, int, decimal, long, short, int - in fact anything enumerable
{
    [...]
    T Value;
    [...]
}

The problem I am trying to solve is how to unpack this by type T.

I want to write this function but don't know how in C#:

public void DoProcessing(List<IObject> objectsToBeProcessed)
{
    foreach(dynamic singleObject in objectsToBeProcessed)
    {
        Type unpackedType = [somehow retrieve the type
        BaseObject<unpackedType> unpackedObject = [do some kind of conversion of singleObject];
        ProcessorClass<unpackedType> processor = new ProcessorClass<unpackedType>();
        processor.Process(unpackedObject);
    }
}

I'm finding this quite hard to put into words but I hope that this explanation gets the idea across. Basically I lose the type information when I build the List<IObject> and I need it back later on when I pass it across into another assembly. I want a single central DoProcessing method that can then delegate by type to instances of generics.

How can I get the type information back?

Or should I just force everything to a double in BaseObject and then cast it back locally in some way?

I'm a bit lost on this and feel I am missing something obvious. Any ideas welcome.





Aucun commentaire:

Enregistrer un commentaire