Params IEnumerable c#

后端 未结 3 1841
暖寄归人
暖寄归人 2020-12-24 10:35

Why cant I use an IEnumerable with params? Will this ever be fixed? I really wish they would rewrite the old libraries to use generics...

3条回答
  •  鱼传尺愫
    2020-12-24 11:00

    Ah, I think I may now have understood what you mean. I think you want to be able to declare a method like this:

    public void Foo(params IEnumerable items)
    {
    }
    

    And then be able to call it with a "normal" argument like this:

    IEnumerable existingEnumerable = ...;
    Foo(existingEnumerable);
    

    or with multiple parameters like this:

    Foo("first", "second", "third");
    

    Is that what you're after? (Noting that you'd want the first form to use T=string, rather than T=IEnumerable with a single element...)

    If so, I agree it could be useful - but it's easy enough to have:

    public void Foo(params T[] items)
    {
        Foo((IEnumerable) items);
    }
    
    public void Foo(IEnumerable items)
    {
    }
    

    I don't find I do this often enough to make the above a particularly ugly workaround.

    Note that when calling the above code, you'll want to explicitly specify the type argument, to avoid the compiler preferring the params example. So for example:

    List x = new List();
    Foo(x);
    

提交回复
热议问题