Overloading params function with IEnumerable

Suppose I have two functions:

Foo(params INotifyPropertyChanged[] items) { //do stuff } Foo<T>(IEnumerable<T> items) where T : INotifyPropertyChanged { Foo(items.ToArray()); } 

The second allows me to call Foo from a generic class with a where T : INotifyPropertyChanged , but the second allows itself, so I get an exception.

  • Can I indicate which overload I want to cause when there is some ambiguity?
  • Is there another way to call the params function from a generic class if the generic type constraints make it viable for the params type?

Thanks in advance!

+4
source share
2 answers

You need to pass INotifyPropertyChanged[] , not T[] .
For instance:

 Foo<T>(IEnumerable<T> items) where T : INotifyPropertyChanged { Foo(items.Cast<INotifyPropertyChanged>().ToArray()); } 

In general, however, it is better to call the IEnumerable version the params version, for example:

 Foo(params INotifyPropertyChanged[] items) { Foo((IEnumerable<INotifyPropertyChanged>) items); } Foo<T>(IEnumerable<T> items) where T : INotifyPropertyChanged { //do stuff } 
+6
source

You can try typing.

 Foo<T>(IEnumerable<T> items) where T : INotifyPropertyChanged { Foo(items.Cast<INotifyPropertyChanged>().ToArray()); } 

If this does not work, I have no idea; you are probably out of luck.

+3
source

Source: https://habr.com/ru/post/1313222/


All Articles