我正在创建一个可以接受泛型类型作为数据的类,如果是集合类型,我想为内部添加元素创建一个扩展方法。到目前为止,我有以下扩展方法:
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存储库中找到:
- https://github.com/Xelit3/CommonNET
编辑:最初,扩展方法的名称被错误地复制了AddData -> AddElement,这要归功于@Fabjan
您可以更改扩展方法以同时采用 T 和 TElement,并约束 T 以强制其成为 IColction:
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);