C# 扩展泛型参数和Func参数泛型参数之间的关系
所以我想我并不真正理解上面的内容。假设您在可枚举类型上有一个扩展,如下所示C# 扩展泛型参数和Func参数泛型参数之间的关系,c#,.net,linq,generics,extension-methods,C#,.net,Linq,Generics,Extension Methods,所以我想我并不真正理解上面的内容。假设您在可枚举类型上有一个扩展,如下所示 public static TElement StringMatch<TElement, TData>( this IEnumerable<TElement> source, Func<TElement, TData> selector) 这是怎么回事?扩展方法中的泛型参数具体指定了什么 public static TElement StringMat
public static TElement StringMatch<TElement, TData>(
this IEnumerable<TElement> source,
Func<TElement, TData> selector)
这是怎么回事?扩展方法中的泛型参数具体指定了什么
public static TElement StringMatch<TElement, TData>(
this IEnumerable<TElement> source,
Func<TElement, TData> selector)
当然,您可以同时实现这两个功能。编译器将选择最具体的一个。调用者还可以显式指定类型参数,只留下一个选项。您的第二个签名将无法编译,因为您要求编译器查找名为“TData”的类型。由于未将其包含在泛型方法定义中,编译器不知道TData应该是泛型类型参数。也许我真的错过了一些东西,但是你能详细说明一下你想要StringMatch做什么吗?哦,这实际上是一个错误,现在编辑…好的,我认为这是有意义的。所以扩展方法的泛型参数只包括该方法的参数中包含的所有泛型参数,而不包括要扩展的枚举?我想让我困惑的是泛型参数和Func参数使用相同的语法,我认为必须有两个泛型参数,因为这两个Func参数在方法或委托名称之后是正式的参数声明。(它们也可以在类/接口声明中的类/接口名称之后。)其他任何地方都是对这些名称的引用。它们可以用于返回类型、参数类型或正文中使用类型的任何地方。(它们甚至可以不用。)
'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)
public static TElement StringMatch<TElement>(
this IEnumerable<TElement> source,
Func<TElement, string> selector)