【发布时间】:2018-02-22 21:57:42
【问题描述】:
我正在尝试对IDbSet<T> 进行模拟实现,而我恰好是在 F# 中进行的。
type MockDbSet<'T when 'T : not struct>(items:seq<'T>) =
let collection = ResizeArray(items)
new () = MockDbSet(Seq.empty)
interface IDbSet<'T> with
member x.Add entity = collection.Add entity; entity
member x.Attach entity = collection.Add entity; entity
member x.Remove entity = collection.Remove entity |> ignore; entity
member x.Create() = Unchecked.defaultof<'T>
member x.Create<'TD when 'TD : not struct and 'TD :> 'T>() = Unchecked.defaultof<'TD>
member x.Find([<ParamArray>] values) = raise <| NotImplementedException()
member x.Local = Collections.ObjectModel.ObservableCollection(collection)
interface System.Collections.Generic.IEnumerable<'T> with
member x.GetEnumerator() =
collection.GetEnumerator() :> System.Collections.Generic.IEnumerator<_>
interface System.Collections.IEnumerable with
member x.GetEnumerator() =
collection.GetEnumerator() :> System.Collections.IEnumerator
interface IQueryable<'T> with
member x.ElementType = typeof<'T>
member x.Expression =
collection.AsQueryable().Expression
member x.Provider =
collection.AsQueryable().Provider
一切都很好,除了这一行:
member x.Create<'TD when 'TD : not struct and 'TD :> 'T>() = Unchecked.defaultof<'TD>
...这给了我这些编译器错误:
错误 FS0698:无效约束:用于约束的类型是 密封,这意味着约束最多只能满足 一种解决方案
警告 FS0064:此构造会导致代码变少 比类型注释所指示的泛型。类型变量 'TD 已被限制为“T”类型。
错误 FS0663:此类型 参数的使用方式将其限制为始终为 ''T 当'T:不是结构'
错误 FS0661:一个或多个显式类 或此绑定的函数类型变量无法泛化, 因为它们被限制为其他类型
此行正在尝试实现this method,根据该页面,它在 C# 中具有以下签名:
TDerivedEntity Create<TDerivedEntity>()
where TDerivedEntity : class, TEntity
F# 中的这个签名:
abstract Create : unit -> 'TDerivedEntity when 'TDerivedEntity : not struct and 'TEntity
当我尝试使用示例 F# 签名时,我遇到了各种语法错误,这并不让我感到惊讶,因为该签名甚至看起来不像是有效的 F#。
我不确定如何处理这些错误消息,或者如何编写约束来满足接口和 F# 编译器的要求。我开始怀疑是否有可能用这种特殊的 Microsoft 编程语言来实现这个特殊的 Microsoft 界面。欢迎提出任何建议。
【问题讨论】:
标签: entity-framework f#