我希望我们在 C# 中有“可用”模式,当 using 构造的代码块将作为委托传递给函数时:
class Usable : IUsable
{
public void Use(Action action) // implements IUsable
{
// acquire resources
action();
// release resources
}
}
在用户代码中:
using (new Usable())
{
// this code block is converted to delegate and passed to Use method above
}
优点:
- 受控执行,异常
- 使用“可用”的事实在调用堆栈中可见
缺点:
- 委托费用
你认为它是否可行和有用,如果从语言的角度来看它没有任何问题?有没有你能看到的陷阱?
编辑:大卫施密特提出以下
using(new Usable(delegate() {
// actions here
}) {}
它可以在这样的示例场景中工作,但通常您已经分配了资源并希望它看起来像这样:
using (Repository.GlobalResource)
{
// actions here
}
GlobalResource(是的,我知道全球资源不好)实现 IUsable 的地方。你可以重写的时间很短
Repository.GlobalResource.Use(() =>
{
// actions here
});
但它看起来有点奇怪(如果你显式地实现接口,那就更奇怪了),而且这种情况在各种风格中都很常见,我认为它应该成为一种语言中的新语法糖。