Reputation: 1051
I have a class who - upon instantiation - creates a background thread that waits for work to do via System.Threading.AutoResetEvent. When work is available, the thread would pull an object from a generic Queue to work on and then call a Callback delegate from the object when finished.
The devil's in the details, though: To do its work, the thread calls a generic function, so a Type needs to be known by the thread. I can define the objects in the queue to accept a generic, but how can I define a queue to accept an object that is truly generic, that is, its type could be anything? How could the background thread infer the type needed for its generic function call?
Example Code:
class GenericItem<T>
{
// ... some code ...
}
// somewhere else in code
Queue<GenericItem> myGenericListofItemsToWorkOn;
Obviously C# doesn't like the last line since I am trying to NOT specify a concrete type so I can do the following:
myGenericListofItemsToWorkOn.Enqueue( new GenericItem<string>() );
myGenericListofItemsToWorkOn.Enqueue( new GenericItem<int>() );
My thread then needs to do the following:
GenericItem obj = myGenericListofItemsToWorkOn.Dequeue(); // How can I reference a generic item here?
Library.Call<...>(...); // How can I infer the generic type of the item dequeued here?
Upvotes: 2
Views: 158
Reputation: 437424
You cannot do this. What you can do is have class GenericItem<T>
implement a non-generic interface (or derive from a non-generic base class) that exposes enough functionality for you to work with. You would then be able to have
Queue<ISomething> myGenericListofItemsToWorkOn;
and when you pull items out of the queue ISomething
should expose enough functionality for you to work on each item.
Update: This is what would never work:
Library.Call<X>(...);
To make such a call the compiler needs to know what X
is, either because you specify it explicitly or because it can infer it from the type of ...
. But since the list contains items of different types you can only tell what you pulled out of the bag at runtime, with GetType()
. You can't have your cake and eat it too; either the Queue
must contain objects of only one type, or Library.Call
must not be "strongly typed".
Upvotes: 2