c# - 优雅地传递列表和对象作为参数

标签 c#

在 C# 中,可以使用 params 关键字为方法指定任意数量的类型化参数:

public void DoStuff(params Foo[] foos) {...}

public void OtherStuff {
    DoStuff(foo1);
    DoStuff(foo2, foo3);
}

如果你已经有了一个对象列表,你可以把它变成一个数组传递给这个方法:

DoStuff(fooList.ToArray());

但是,有什么优雅的混合搭配方式吗?也就是说,传入多个对象和对象列表,然后将结果扁平化为一个列表或数组?理想情况下,我希望能够像这样调用我的方法:

DoStuff(fooList, foo1, foo2, anotherFooList, ...);

截至目前,我知道如何执行此操作的唯一方法是将所有内容预处理到一个列表中,但我不知道有什么方法可以通用地执行此操作。

编辑:需要明确的是,我没有与 params 关键字结合,它只是一个相关机制,可以帮助我解释我想做什么。我对任何看起来干净并将所有内容扁平化到一个列表中的解决方案都非常满意。

最佳答案

您可以创建一个具有隐式转换的类来包装单个元素和一个列表:

public class ParamsWrapper<T> : IEnumerable<T>
{
    private readonly IEnumerable<T> seq;

    public ParamsWrapper(IEnumerable<T> seq)
    {
        this.seq = seq;
    }

    public static implicit operator ParamsWrapper<T>(T instance)
    {
        return new ParamsWrapper<T>(new[] { instance });
    }

    public static implicit operator ParamsWrapper<T>(List<T> seq)
    {
        return new ParamsWrapper<T>(seq);
    }

    public IEnumerator<T> GetEnumerator()
    {
        return this.seq.GetEnumerator();
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }
}

然后您可以将DoStuff 方法更改为:

private static void DoStuff(params ParamsWrapper<Foo>[] foos)
{
    Foo[] all = foos.SelectMany(f => f).ToArray();
    //
}

关于c# - 优雅地传递列表和对象作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18066489/

相关文章:

c# - 将 ZIP 文件插入数据库

c# - NullReferenceException:用户单击按钮时为 "Object reference not set to an instance of an object"

c# - Entity Framework - 查询以获取列的最后 2 个唯一条目及其相关数据

c# - Linq 查询一个集合内的集合、来自另一个集合的集合

c# - Azure 阻止上传和输入流

c# - 如何获取列表框中的项目数

c# - Spring 在 nhibernate 事务后不关闭 session

c# - WCF 服务 - 向后兼容性问题

c# - C#中静态变量有什么用?什么时候使用它?为什么我不能在方法内部声明静态变量?

c# - 用相同的数字填充列表