gpt4 book ai didi

entity-framework - 是否可以在 F# 中实现 IDbSet 接口(interface)?

转载 作者:行者123 更新时间:2023-12-03 15:39:38 25 4
gpt4 key购买 nike

我正在尝试模拟实现 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>

...这给了我这些编译器错误:

error FS0698: Invalid constraint: the type used for the constraint is sealed, which means the constraint could only be satisfied by at most one solution

warning FS0064: This construct causes code to be less generic than indicated by the type annotations. The type variable 'TD has been constrained to be type ''T'.

error FS0663: This type parameter has been used in a way that constrains it to always be ''T when 'T : not struct'

error FS0661: One or more of the explicit class or function type variables for this binding could not be generalized, because they were constrained to other types



此行正在尝试实现 this method ,根据该页面,它在 C# 中具有以下签名:
TDerivedEntity Create<TDerivedEntity>()
where TDerivedEntity : class, TEntity

F# 中的这个签名:
abstract Create : unit -> 'TDerivedEntity  when 'TDerivedEntity : not struct and 'TEntity

当我尝试使用示例 F# 签名时,会遇到各种语法错误,这并不让我感到惊讶,因为该签名甚至看起来都不像有效的 F#。

我不确定如何处理这些错误消息,或者如何编写约束以满足接口(interface)和 F# 编译器。我开始怀疑是否有可能用这种特殊的 Microsoft 编程语言来实现这个特殊的 Microsoft 界面。任何建议都会受到欢迎。

最佳答案

方法Create需要 2 个泛型类型参数之间的子类型约束。恐怕没有办法将子类型约束添加到基于 F# 中另一个的泛型类型参数。它们总是被假定为相等的,见 spec表单 type :> 'b 的新约束再次解决为 type = 'b.

看到这个相关的answer到类似的问题。

我们应该要求包括this下一个 F# 版本中的功能。

关于entity-framework - 是否可以在 F# 中实现 IDbSet<T> 接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23643989/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com