在 f# 项目中,我有以下类型:
type A = { Name: string }
type B = { Name: string; SurName: string }
type C = { Name: string; SurName: string; MaidenName: string }
以及以下使用泛型参数约束的函数:let inline filterByName<'a when 'a: (member Name: string)> (name: string) (collection: 'a seq) =
collection |> Seq.where(fun i -> i.Name = name)
问题是我收到以下编译时错误:Type constraint mismatch. The type
'a
is not compatible with type
C
The type ''a' does not match the type 'C'
删除
inline
从函数定义给了我以下编译时错误:This code is not sufficiently generic. the type variable ^a when ^a:(member get_Name: ^a -> string) could not be generalized because it would escape its scope.
我想要实现的是有一个函数,它采用具有特定名称的属性的泛型类型,在本例中为“名称”。我做错了什么或我错过了什么?
最佳答案
问题在于您如何调用受约束的成员 - 您不能使用 i.Name
语法,但必须使用更详细的语法。从好的方面来说,这可以推断方法本身的签名,因此您不必复制所有内容:
let inline filterByName name collection =
collection |> Seq.where(fun i -> (^a : (member Name : string) i) = name)
另请注意,您需要使用静态解析的类型变量 (
^a
) 而不是普通的泛型类型变量 ( 'a
)。
关于.net - 在泛型函数上使用约束时 F# 类型约束不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35184052/