如何使用泛型类型重构几乎重复的方法

发布于 2024-11-28 02:14:54 字数 743 浏览 0 评论 0原文

我有一些几乎相同的方法,只是它们具有不同数量的泛型类型参数。内部代码非常非常相似:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

悸初 2024-12-05 02:14:54

也许您可以为集合创建一个构建器,例如

public class SetCollectionBuilder
{
    private readonly List<Set> sets = new List<Set>();
    public SetCollectionBuilder Add<T>(List<T> list)
    {
        this.sets.Add(CreateSet(list));
        return this;
    }

    public Set[] Build()
    {
        return this.sets.ToArray();
    }
}

然后您可以创建一个任意集合,例如:

Set[] result = new SetCollectionBuilder()
    .Add(first)
    .Add(second)
    .Build();

Maybe you could create a builder for the set collection e.g.

public class SetCollectionBuilder
{
    private readonly List<Set> sets = new List<Set>();
    public SetCollectionBuilder Add<T>(List<T> list)
    {
        this.sets.Add(CreateSet(list));
        return this;
    }

    public Set[] Build()
    {
        return this.sets.ToArray();
    }
}

Then you could create an arbitrary collection like:

Set[] result = new SetCollectionBuilder()
    .Add(first)
    .Add(second)
    .Build();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文