gpt4 book ai didi

c# - 扩展泛型参数与 Func argument 泛型参数的关系

转载 作者:行者123 更新时间:2023-11-30 22:07:12 24 4
gpt4 key购买 nike

所以我想我并没有真正理解上面的内容。就像假设你有一个像这样的可枚举类型的扩展......

public static TElement StringMatch<TElement, TData>(
this IEnumerable<TElement> source,
Func<TElement, TData> selector)

这里一切都很好,但我一直假设 StringMatch 泛型参数反射(reflect)了 Func 泛型参数,因为 Func<>在用户看来是要传递的内容。

但是假设我想指定 Func<> 的返回类型是一个特定的参数,可能像Func<TElement, string>

现在我的想法是像这样更改签名...

public static TElement StringMatch<TElement, string>(
this IEnumerable<TElement> source,
Func<TElement, string> selector)

...再次反射(reflect)传递的 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 的情况,其中 TDatastring

如果您希望 TData 始终是特定类型 string 则只需将其作为方法中的形式通用参数删除即可:

public static TElement StringMatch<TElement>(
this IEnumerable<TElement> source,
Func<TElement, string> selector)

当然,您可以同时实现两者。编译器将选择最具体的一个。调用者也可以显式指定类型参数,只留下一个选择。

关于c# - 扩展泛型参数与 Func argument 泛型参数的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23166066/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com