F#泛型约束

时间:2014-06-26 12:26:07

标签: .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

这是开源项目

1 个答案:

答案 0 :(得分:2)

我不知道为什么我的代码显示了错误消息,但我找到了解决方法并且我在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

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

问题中的方法保持不变。