一个或多个参数

Vla*_*ani 6 c# parameters methods refactoring

我有两种方法:

BuildThing(Thing a);
BuildThings(IEnumerable<Thing> things);
Run Code Online (Sandbox Code Playgroud)

从干净的代码角度看这是好事吗?或者也许最好只使用BuildThings并只用一个东西传递IEnumerable?或者使用params?

谢谢.

Mik*_*erg 10

你可以做一件事:

BuildThings(params Thing[] things);
Run Code Online (Sandbox Code Playgroud)

这使您可以使用:

BuildThings(thing1, thing2, thing3, ...);
Run Code Online (Sandbox Code Playgroud)


Dar*_*o Z 6

我个人的偏好如下

接口:

void Build(Thing thing);
void Build(IEnumerable<Thing> things);
Run Code Online (Sandbox Code Playgroud)

执行:

void Build(Thing thing)
{
    Build(new [] { thing });
}

void Build(IEnumerable<Thing> things)
{
    //do stuff
}
Run Code Online (Sandbox Code Playgroud)

我更喜欢使用这种模式的原因是因为它确保你保持DRY同时为你提供多次重载的灵活性,这与params你必须将任何非数组可枚举转换为数组的方式不同.