Is there anyway I can do this?
class TSOC<TCollection, TValue> : ICollection<TValue>, INotifyCollectionChanged where TCollection : ICollection
{
private TCollection<TValue> collection;
}
It doesn’t like my definition of collection. I’d prefer the definition to look like TSOC<TCollection> where the user can pass in List<int> or something, but then I need to pull out the “int” to know what interface to implement.
Basically I just wanted to wrap all the ICollection methods in locks and force them to run on a particular thread, but still keep all the additional functionality of the programmer’s collection of choice…. I’m not sure this is possible though.
How about:
I think this is what you’re looking for. It seems like maybe you’re trying to wrap a generic collection, and you want the first type of parameter to be an existing collection of the same type. This will give you exactly that.
Hard to say, but you might not even need that. Unless you really need to know the underlying type of the
TCollectionobject, you could probably just make it aTSOC<TValue>and accept anICollection<TValue>to wrap it with:This is functionally the same thing, you just won’t have knowledge of the actual underlying type of the
ICollection<TValue>.Update:
Responding now to this edit:
I think you actually could achieve what you want, but perhaps in a slightly different way than you expect. You don’t even really need the collection, you just want a synchronized wrapper:
Then use it as:
Now I know this isn’t exactly what you want, since it doesn’t actually give you an instance of
ICollection<T>you can pass around. But it’s a clean encapsulation of the locking behaviour and hides the inner collection, so you can guarantee that every operation is “thread safe.”If you really, really need an equivalent instance of
ICollection<T>that wraps anotherICollection<T>while adding thread safety, then what you’re actually looking for is method interception using a library like Castle DynamicProxy.