dot*_*ter 14 .net c# functional-programming
它是等同的吗?
public static void Using<T>(this T disposable, Action<T> action)
where T:IDisposable
{
try {
action(disposable);
}
finally {
disposable.Dispose();
}
}
new SqlConnection("").Using(conn => {
});
using(var conn = new SqlConnection("")){
};
Run Code Online (Sandbox Code Playgroud)
换句话说,我们可以用这种方法替换关键字吗?
Mar*_*ann 19
我不认为这是一个特别好的主意,因为它也可以让我们写
var conn = new SqlConnecction("");
conn.Using(c => /* do something with c */);
conn.Open();
Run Code Online (Sandbox Code Playgroud)
这将编译,但是当你到达最后一行时,它将抛出一个ObjectDisposedException.
在任何情况下,using编码习惯都是众所周知的,那么为什么让你的开发人员更难以阅读你的代码呢?
Eri*_*ert 10
我注意到你的方法没有做"使用"语句所做的所有事情.例如,它没有引入新的局部变量声明空间,在该空间中可以声明保留在资源上的变量.
它也不允许一次性声明多个相同类型的一次性资源.
最后,它似乎并没有特别优雅地与自己构成.关于"使用"作为陈述的好处之一是你可以说:
using(something)
using(someotherthing)
using(somethirdthing)
{
use all three, they'll all get disposed
}
Run Code Online (Sandbox Code Playgroud)
你的提案会怎么样?
something.Using(
x=>someotherthing.Using(
y=>somethirdthing.Using(
z=> { use all three } )));
Run Code Online (Sandbox Code Playgroud)
坦率地说,有点严重.