.net - F# 泛型约束

标签 .net generics f# constraints f#-3.0

我在类里面有这个方法:

member this.GetDbSet<'TEntity, 'TDTO, 'TKey when 'TKey :> IEquatable<'TKey> and 'TEntity :> IEntity<'TKey> and 'TEntity : not struct and 'TDTO :> IDTO<'TKey> and 'TEntity : equality and 'TEntity : null and 'TDTO : equality and 'TDTO : null and 'TKey : equality>(repository : BaseRepository<'TEntity, 'TDTO, 'TKey>) = 
    repository.DbSetFuncGetter().Invoke(uow.Context())

但是当我构建项目时出现这个错误

This code is not sufficiently generic. The type variable 'TEntity when 'TEntity :> IEntity<'TKey> and 'TEntity : not struct and 'TEntity : equality and 'TEntity : null and 'TKey :> IEquatable<'TKey> and 'TKey : equality could not be generalized because it would escape its scope.

但是所有限制都在那里。我错过了什么吗?

编辑:

如果您需要更多代码:

https://github.com/Ar3sDevelopment/Caelan.Frameworks.BIZ/blob/fsharp/Caelan.Frameworks.BIZ/Classes.fs

这是开源项目

最佳答案

我不知道为什么会为我的代码显示该错误消息,但我找到了解决方法并提交了 GitHub 项目。您可以检查此文件的差异,因为它更容易阅读而不是描述它。

https://github.com/Ar3sDevelopment/Caelan.Frameworks.BIZ/commit/22898671635b4667c8741853af9cc86910e1ff5a#diff-d5779b1053a390520d2a4a0c643f3d68

链接包含解决问题的差异,但我将在下几行中解释。

我用变通方法解决了它,我不知道它为什么会显示。

在存储库类(问题中存储库的类,不是方法的类)上有这些成员:

let mutable dbSetFunc : Func<DbContext, DbSet<'TEntity>> = null
member this.DbSetFunc 
    with set (value) = dbSetFunc <- value
member this.DbSetFuncGetter() = dbSetFunc

但是他们产生了错误,我发现它试图评论他们,我把他们改成了这些

[<DefaultValue>] val mutable dbSetFunc : Func<DbContext, DbSet<'TEntity>>
member this.DbSetFunc 
    with set (value) = this.dbSetFunc <- value
member internal this.DbSetFuncGetter() = this.dbSetFunc

而且我无法解释为什么这可以解决错误,至少我希望这会有所帮助。

问题中的方法保持不变。

关于.net - F# 泛型约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24430515/

相关文章:

c# - Toast 显示不止一次

f# - 在 HTML 解析器中按类或 id 查找对象

c# - 带有 F# : System. InvalidOperationException 的 Swashbuckle:'无法找到所需的服务

f# - 序列头尾

.net - 制作你自己的 "int"或 "string"类

c# - 如何在 C# 中读取 MKV 电影文件的长度和其他信息?

c# - 更改 RichTextBox 中选定文本的样式

swift - 为什么我的简单协议(protocol)只能用作通用约束?

c# - 如何将两个 C# 列表拼接成一个?或者可能使用不同的集合类型?

java - 使用 lambda 会阻碍类型变量的推断