4

Suppose I have two functions:

Foo(params INotifyPropertyChanged[] items)
{
   //do stuff
}

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

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

  1. Is it possible to specify which overload I want to call when there's some ambiguity?
  2. Is there another way to call a params function from a generic class, assuming the generic type's constraints make it a viable option for the params type?

Thanks in advance!

4

2 回答 2

7

你需要通过 a INotifyPropertyChanged[],而不是 a T[]
例如:

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

但是,一般来说,最好IEnumerable从版本中调用params版本,如下所示:

Foo(params INotifyPropertyChanged[] items)
{
   Foo((IEnumerable<INotifyPropertyChanged>) items);
}

Foo<T>(IEnumerable<T> items) where T : INotifyPropertyChanged
{
   //do stuff
}
于 2010-06-18T20:29:23.897 回答
3

您可以尝试投射输入。

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

如果这不起作用,我不知道,你可能不走运。

于 2010-06-18T20:29:00.587 回答