.net - F# 代码不够通用(使用静态成员约束)

标签 .net f# blazor bolero

我正在尝试创建一个通用函数,该函数检查记录是否采用有效格式,前提是该记录实现了静态成员 valid。当尝试在 Bolero (Blazor) 框架内的 ElmishComponent 中使用它时,我收到以下错误

This code is not sufficiently generic. The type variable ^childModel when ^childModel : (static member valid : ^childModel -> bool) could not be generalized because it would escape its scope

使用以下代码

module Modal =
    type Message<'childModel, 'childMessage> = | Confirm of 'childModel | Cancel | ChildMessage of 'childMessage
    type Model<'T> = { Display : bool; Title : string; Child : 'T }
    let inline valid (x: ^t) =
        (^t: (static member valid: ^t -> bool) (x))

    type Component<'T, ^childModel, 'childMessage when 'T :> ElmishComponent< ^childModel, 'childMessage> and ^childModel : (static member valid: ^childModel -> bool)>() =
        inherit ElmishComponent<Model<'childModel>, Message<'childModel, 'childMessage>>()

        // Error is highlighted on this line
        override this.View model dispatch = 
            cond model.Display <| function
            | true ->
                div [ attr.style (if model.Display then "background: lightblue;" else "background: grey;") ] [
                    h3 [] [ text model.Title ]
                    ecomp<'T,_,_> model.Child (dispatch << ChildMessage)
                    p [] []
                    button [ 
                        // This is where I use the valid function
                        attr.disabled (if valid model.Child then null else "true")
                        on.click (fun _ -> dispatch <| Confirm model.Child)
                    ] [ text "Confirm" ]
                    button [ on.click (fun _ -> dispatch Cancel) ] [ text "Cancel" ]
                ]
            | false ->
                empty

最佳答案

我可能遗漏了一些东西,但在我看来,一种更简单的方法是使用子模型实现的接口(interface) - 那么你根本不必担心静态成员约束:

type IValidable =
  abstract IsValid : bool

type Component<'T, 'childModel, 'childMessage when 
      'T :> ElmishComponent< 'childModel, 'childMessage> and 
      'childModel :> IValidable>() =
    inherit ElmishComponent<Model<'childModel>, Message<'childModel, 'childMessage>>()
    override this.View model dispatch = 
        let test = model.Child.IsValid            
        ()

关于.net - F# 代码不够通用(使用静态成员约束),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54221696/

相关文章:

C# 属性 AppSettings

f# - 是否可以强制记录尊重某些不变量?

f# - 在哪里可以找到最新的 F# 核心库引用?

.net - 使用 Blazor 在 Azure 上出现 POST 405(不允许的方法)错误,但在 localhost 上一切正常

azure-devops - Blazor 路由在 Azure DevOps iframe 中失败

.net - 如何在自动构建中避免 .NET 项目中的 Authenticode 签署第三方库?

c# - .NET中的语音识别器日期时间

c# - 比较 XML 文件是否相等的最佳方法是什么?

interface - F#:未找到与此覆盖对应的抽象属性

c# - 值不能为空。参数名称 : source when trying to get data with web api