.net - 在泛型函数上使用约束时 F# 类型约束不匹配

标签 .net f# inline

在 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/

相关文章:

c# - 为什么我的 C# 应用程序在多线程单元上运行?

javascript - Vue 获取发布数据到 Controller asp.net mvc

c# - TimeSpan 到 ISO8601 持续时间格式字符串

css - 将一个 div 放置在两个图像旁边,这两个图像内联显示在一个包含 div 的图像中

c++ - 访问静态变量时内联函数和静态内联函数之间的区别

c# - 使用 ToArgb() 后跟 FromArgb() 不会产生原始颜色

.net - 如何在 Linux 上的 Visual Studio Code 中下载 dotnet 项目中的 nuget 依赖项源?

c# - "Object Expression"是否像 F# 一样存在于 C# 中?

f# - 使用列表中的 Discriminated union 测试相等性

c++ - 应该在共享库头文件中使用内联函数吗?