所以我想我不太明白上面的内容。就像假设您有一个可枚举类型的扩展,如下所示......
public static TElement StringMatch<TElement, TData>(
this IEnumerable<TElement> source,
Func<TElement, TData> selector)
这里一切都很好,但我一直假设 StringMatch 通用参数镜像 Func 通用参数,因为 Func<>
是用户认为要传递的内容。
但假设我想指定 Func<>
的返回类型是一个特定的参数,可能像 Func<TElement, string>
现在我的想法是像这样改变签名......
public static TElement StringMatch<TElement, string>(
this IEnumerable<TElement> source,
Func<TElement, string> selector)
...再次,镜像传递的 Func<>。但是如果我尝试在 Books.StringMatch(b => b.Title)
之类的东西上调用它,我收到一个错误,例如...
'Book' does not contain a definition for 'StringMatch' and no extension method 'StringMatch' accepting a first argument of type 'Book' could be found (are you missing a using directive or an assembly reference?)
那么这是怎么回事呢?扩展方法中的通用参数到底指定了什么?
最佳答案
一旦你有了
public static TElement StringMatch<TElement, TData>(
this IEnumerable<TElement> source,
Func<TElement, TData> selector)
它涵盖了调用者传递 Func
的情况,其中 TData
是 string
。
如果您希望 TData
始终为特定类型 string
,那么只需将其作为方法中的正式泛型参数删除即可:
public static TElement StringMatch<TElement>(
this IEnumerable<TElement> source,
Func<TElement, string> selector)
当然,您可以同时实现两者。编译器将选择最具体的一个。调用者还可以显式指定类型参数以仅留下一种选择。
关于c# - 扩展泛型参数和 Func 参数泛型参数之间的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23166066/