Is it possible to compose two interfaces and duck type a class to the composition?
I have a class that inherits from ObservableCollection<T>
to re-use the INotifyCollection
functionality, but acts开发者_开发技巧 like a HashSet
. I've called it ObservableHashSet<T>
. I use both ObservableCollection
and ObservableHashSet
in my app.
I've reached a point where I want to pass either an ObservableCollection
or an ObservableHashSet
into a method, but the only functionality I'm interested in is IEnumerable<T>
and INotifyCollectionChanged
.
My question is: is it possible to have a single method that takes as its parameter either of these classes? i.e.
ObservableCollection<IExample> a = new ...
ObservableHashSet<IExample> b = new ...
MyMethod(a);
MyMethod(b);
I'm using .NET 4, in case there are any juicy features in there that are useful...
If you've inherited from ObservableCollection
then using that as the parameter type should work.
I've found a nice solution, use a generic method and constrain the type parameter with the two interfaces I need:
public void MyMethod<T>(T collection) where T : IEnumerable<IExample>, INotifyCollectionChanged
{
}
This seems to do the trick nicely. I'd welcome any comments on doing it this way though :)
精彩评论