【发布时间】:2018-12-04 19:48:06
【问题描述】:
目标:泛型枚举类型返回时为同一类型。
注意:这在输入类型时有效,但我不明白为什么不能推断它们。
List<T> 然后返回List<T>
IOrderedEnumerable<T> 然后返回IOrderedEnumerable<T>
ETC
当前方法(仅在输入所有类型时有效)
public static TEnumerable WithEach<TEnumerable, T>(this TEnumerable items, Action<T> action)
where TEnumerable : IEnumerable<T>
{
foreach (var item in items) action.Invoke(item);
return items;
}
仅作为示例
var list = new List<int>(); //TODO: Mock random values
list.WithEach(x => Console.WriteLine(x)) //Here WithEach ideally returns List<int> following orignal type List<int>
.OrderBy(x => x)
.WithEach(x => Console.WriteLine(x)); //Here WithEach ideally returns IOrderedEnumerable<int> following OrderBy
让它发挥作用
var list = new List<int>(); //TODO: Mock random values
list.WithEach<List<int>, int>(x => Console.WriteLine(x))
.OrderBy(x => x)
.WithEach<IOrderedEnumerable<int>, int>(x => Console.WriteLine(x));
我缺少的是为什么 C# 不能推断类型,尽管 where 过滤器确实使类型准确。我理解您为什么要为方法提供全部或不提供泛型类型,所以请不要向我指出这些答案。
编辑:如果我无法推断类型;那我怎样才能让它更优雅呢?
【问题讨论】:
-
我会研究细节,但只是作为一个警告:这最终会迭代序列,然后返回相同的序列,可能不支持被迭代多次。在设计类似 LINQ 的方法时,我尽量避免多次迭代。在你的情况下这可能不是问题,但我想我会在研究类型推断之前提到它。
-
你是对的@JonSkeet;理想情况下,迭代是不可变的。我只是在摸索使方法流利并保持问题简单。
-
为什么不
yield? -
@KennethK.:鉴于声明的目标是“通用枚举类型在返回时是相同的类型”。这听起来像是对您问题的回答。 (例如,在调用
OrderBy然后WithEach之后,使用OP 的设计,他们可以调用ThenBy- 如果WithEach只返回IEnumerable<T>,他们就不能。) -
@Servy:我想说的是,为什么类型也没有被推断出来是有区别的——这个问题在 anywhere 中没有第二个类型参数参数列表;确实如此,但该论点无助于推断。对于类型推断,我认为有多个有点相似但有细微差别的问题很有用。
标签: c# extension-methods generic-collections