如何使用泛型类型重构几乎重复的方法
我有一些几乎相同的方法,只是它们具有不同数量的泛型类型参数。内部代码非常非常相似:
public Set[] CreateSet<TFirst, TSecond>(List<TFirst> first, List<TSecond> second)
{
Set[] result = new Set[2];
result[0] = CreateSet(first);
result[1] = CreateSet(second);
return result;
}
public Set[] CreateSet<TFirst, TSecond, TThird>(List<TFirst> first, List<TSecond> second, List<TThird> third)
{
Set[] result = new Set[3];
result[0] = CreateSet(first);
result[1] = CreateSet(second);
result[2] = CreateSet(third);
return result;
}
...
等等。我的这些方法最多有 7 个泛型类型参数。正如您所看到的,它们几乎完全相同,只是它们创建了不同大小的集合数组。
我不喜欢这种代码重复,因此是否可以将此代码重构为内部调用的单个私有方法。或者我应该考虑任何其他方式来执行此操作?
I have a few methods that are practically the same except they have a different number of generic type parameters. Inner code is very very similar:
public Set[] CreateSet<TFirst, TSecond>(List<TFirst> first, List<TSecond> second)
{
Set[] result = new Set[2];
result[0] = CreateSet(first);
result[1] = CreateSet(second);
return result;
}
public Set[] CreateSet<TFirst, TSecond, TThird>(List<TFirst> first, List<TSecond> second, List<TThird> third)
{
Set[] result = new Set[3];
result[0] = CreateSet(first);
result[1] = CreateSet(second);
result[2] = CreateSet(third);
return result;
}
...
And so on. I have these methods up to 7 generic type parameters. As you can see they're practically all the same except that they create a different size array of sets.
I don't like this code duplication so would it be possible to refactor this code into a single private method that these would internally call. Or should I consider any other way of doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
也许您可以为集合创建一个构建器,例如
然后您可以创建一个任意集合,例如:
Maybe you could create a builder for the set collection e.g.
Then you could create an arbitrary collection like: