我将如何限制其不起作用? [英] how would I constrain to non-function?

查看:92
本文介绍了我将如何限制其不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究将System.Data.IDbConnection及其同级符号抽象出来的代码.

I'm working on code that abstracts away System.Data.IDbConnection and its siblings.

目标代码

let inline runWithConnection connector f = 
        match connector with
        | ICon con -> f con
        | CString cs -> 
            use conn = new SqlConnection(cs)
            openConnection conn
            f conn

我可以看到类型约束可以编译并运行,但是约束对象并没有达到预期的效果.我想约束一个对象或值,该对象或值不是需要更多输入才能返回内容的函数.另外,也可以这样写:如果它确实返回一个函数,则直到完成f为止,可能会关闭可能创建的连接.

I can see that type constraints compile and run, but constraining to object doesn't have the intended effect. I want to constrain to an object or value that is not a function that needs more inputs to return something. Alternatively write this in such a way that if it does return a function the possibly created connection isn't closed until f is done with it.

let inline runWithConnection connector (f:_ -> 't when 't :> obj) = 
        match connector with
        | ICon con -> f con
        | CString cs -> 
            use conn = new SqlConnection(cs)
            openConnection conn
            f conn

看来您可以说't : not struct,但您不能说't: not delegate

It seems you can say 't : not struct but you can't say 't: not delegate

我考虑过要做f.GetType(),但是后来我不知道像.IsClass.IsAbstract.IsValue这样的类型属性将与委托类型一致,而不是与其他简单类型一致.同样,这将是运行时而不是编译时,并不能真正改善情况.

I thought about doing f.GetType() but then I have no idea which type properties like .IsClass, .IsAbstract, .IsValue would be consistent with delegate types as opposed to other simple types. Also that would be run-time instead of compile time, not really improving the situation.

推荐答案

我想你说的是,当您用咖喱f调用runWithConnection时,这是行不通的,因为连接是在第一个之后返回部分函数.

I think what you're saying that this doesn't work when you call runWithConnection with a curried f as the connection is disposed after the first partial function is returned.

没有泛型约束可以解决此问题,因为您不能将约束约束到不是某种东西(即函数)的类型. F#,C#,Java等都一样.

No generic constraints will solve this as you can't constrain to a type that isn't something i.e. a function. This is the same across F#, C#, Java etc.

您可能会抛出运行时异常,但是我认为重新访问您尝试的模式要容易得多.我想问一下,让外部函数执行它传递的函数,而不是仅仅将生成的连接返回为IDisposable来保存什么.这将使调用函数控制连接的范围,例如:

You could possibly throw a runtime exception, but I think it's much easier to revisit the pattern you're attempting. I'd ask what you save by having the outer function execute the function it's passed, rather than just returning the generated connection as an IDisposable. This would let the calling function control the scope of the connection, e.g.:

use conn = getConnection myConnector
doSomethingWithConnection conn anotherArg

这篇关于我将如何限制其不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆