方法处置功能 C#
有没有办法在 C# 2010 (.Net 4) 中不使用 try-finally 块来处理方法变量?
故事: 我有几个文件处理程序方法。每个处理程序(方法)都可以在执行过程中中止。 我喜欢在退出方法之前处理所有方法的对象。 为每个处理程序编写 dispose 方法的选项不是一个选项。
谢谢
这展示了总体思路: `公共静态类比较 { 私有静态 bool CompareXmls(...) { //有7个对象根据4个条件在3个出口点被处理
//General method flow:
//1. init part of the object
//2. if(!<condition1>)
//disposed objects
//exit method
//3. perform some actions
//4. init some of the other objects
//2. if(!<condition2>)
//disposed objects
//exit method
//and so on...
}
private static bool CompareJpgs(...)
{
//has 12 object to be disposed in 10 exit points acordding to 4 conditions
}
private static bool CompareBitMaps(...)
{
//has 5 object to be disposed in 3 exit points acordding to 4 conditions
}
private static bool CompareTxts(...)
{
//has 12 object to be disposed in 10 exit points acordding to 4 conditions
}
}`
我还有另外7个比较方法
Is there a way to dispose method variables without using try-finally block in C# 2010 (.Net 4)?
The story:
I have few files handler methods. Each handler (method) can abort in the middle of execution.
I like to dispose all method's object before exiting the method.
The option to compose dispose method for each handler is not an option.
Thank you
This demonstrate the general idea:
`public static class Comparison
{
private static bool CompareXmls(...)
{
//has 7 object to be disposed in 3 exit points acordding to 4 conditions
//General method flow:
//1. init part of the object
//2. if(!<condition1>)
//disposed objects
//exit method
//3. perform some actions
//4. init some of the other objects
//2. if(!<condition2>)
//disposed objects
//exit method
//and so on...
}
private static bool CompareJpgs(...)
{
//has 12 object to be disposed in 10 exit points acordding to 4 conditions
}
private static bool CompareBitMaps(...)
{
//has 5 object to be disposed in 3 exit points acordding to 4 conditions
}
private static bool CompareTxts(...)
{
//has 12 object to be disposed in 10 exit points acordding to 4 conditions
}
}`
I have another 7 comparison methods
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
?有关如何以及为何使用 的完整说明,请参阅此处http://msdn.microsoft.com/en-us/library/yh598w02(v=VS.100).aspx。一个示例是从
using
块退出后,其标头中声明的所有一次性对象都将被释放。如果您的一次性对象属于不同类型,则可以使用嵌套
using
:using
? Refer here for the full description on how and why to use http://msdn.microsoft.com/en-us/library/yh598w02(v=VS.100).aspx. A sample would beafter exiting from the
using
block, all disposable objects declared in its header will be disposed.If your disposable objects are of different types, you can use nested
using
s:我会将该方法放在一个 idisposible 的对象上并调用finally 块中的 this.dispose()
I would put the method on an object that impiments idisposible and call this.dispose() in a finally block