所以我想我并不是真的了解上述情况。就像假设你有一个类似的可枚举类型的扩展....
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&lt;&gt;。但是如果我尝试在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?)
那么这笔交易是什么? 完全扩展方法中的泛型参数指定了什么?
答案 0 :(得分:3)
一旦你
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)
当然,你可以实现这两个目标。编译器将选择最具体的一个。调用者还可以明确指定类型参数,只留下一个选择。