【发布时间】:2018-02-02 09:16:14
【问题描述】:
我在我的 C# 中使用自定义扩展方法:
//version 1
public static IEnumerable<TSource> ForEachAndReturnSelf<TSource>(this IEnumerable<TSource> container, System.Action<TSource> delegateAction)
{
foreach (var v in container) delegateAction(v); return container;
}
正如你可能猜到的,这个方法是一个稍微调整过的版本:
System.Collections.Generic.List<T>.ForEach()
唯一不同的是我的方法返回自身(不是 void):
无论如何,该版本的方法运行良好。
但是我有这个方法的新版本,它返回原始类型而不是IEnumerable<TSource>。
于是我把方法改成了这样:
//version 2
public static T ForEachAndReturnSelf<T,TSource>(this T container, System.Action<TSource> delegateAction) where T : IEnumerable<TSource>
{
foreach (var v in container) delegateAction(v); return container;
}
因为我需要这样使用它:
//Example Usage1
List<int> list = /* initialize */;
list.ForEachAndReturnSelf(_ => _ *= 2).Convert(_ => _.ToString()).Sort();
//Example Usage2
list.ForEachAndReturnSelf(_ => _ *= 2)[0] = 4;
但是当我将版本 1 更改为 2 时,使用此方法的所有代码部分现在都会产生编译器错误:
方法的类型参数
ExtentionMethods.ForEachAndReturnSelf<T,TSource>(this T, System.Action<TSource>)无法从用法中推断出来。尝试 明确指定类型参数
问题是:
我认为提供的类型信息足以推断类型,但为什么不能呢?
以及如何满足提供类型知识,以便返回与提供的原始类型相同的类型?
【问题讨论】:
-
什么是
T?它是在哪里定义的?
标签: c# .net generics type-inference