为ICollection创建ExtensionMethod,以接受继承的集合类型

时间:2018-10-15 17:24:27

标签: c# .net .net-core extension-methods

我正在创建一个可以接受通用类型作为数据的类,并且如果是集合类型,我想为其中的Add元素创建扩展方法。现在,我有以下扩展方法:

public ActionResponseBuilder<ICollection<TElement>> AddElement<TElement>(this ActionResponseBuilder<ICollection<TElement>> builder, TElement element)
{
    //TODO Logic
    return builder;
}

我的测试方法

var data = DateTime.Now;

var builtActionResponse = new ActionResponseBuilder<List<DateTime>>()
       .SetData(new List<DateTime> { data })
       .AddElement(data)
       .Build();

但是我遇到以下错误:

  

错误CS1929'ActionResponseBuilder>'不包含'AddElement'的定义,最佳扩展方法重载'ActionResponseBuilderHelper.AddElement(ActionResponseBuilder>,DateTime)'需要类型为'ActionResponseBuilder>的接收器

如果我将扩展方法的类型更改为List,它可以工作,但是我想利用继承和泛型的优势,

我所缺少的,我能做到吗?有想法吗?

非常感谢您:)

PD :这些东西是一个小nuget工具的一部分,除此新实现之外的所有代码都可以在以下GitHub存储库中找到:

EDIT :最初,由于@Fabjan

,扩展方法的名称被错误地复制了AddData-> AddElement。

1 个答案:

答案 0 :(得分:3)

您可以更改扩展方法以同时使用T和TElement并约束T以使其成为ICollection:

public static class Extensions
{
    public static ActionResponseBuilder<T> AddData<T, TElement>(this ActionResponseBuilder<T> builder, TElement element) where T : ICollection<TElement>
    {
        // TODO: Logic

        return builder;
    }
}

现在您可以像这样引用它:

ActionResponseBuilder<List<DateTime>> builder = new ActionResponseBuilder<List<DateTime>>()
    .AddData(DateTime.Now);
相关问题