简体   繁体   English

方法处理功能 C#

[英]Method dispose functionality C#

Is there a way to dispose method variables without using try-finally block in C# 2010 (.Net 4)?有没有办法在不使用 C# 2010 (.Net 4) 中的 try-finally 块的情况下处理方法变量?

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.我喜欢在退出方法之前处理所有方法的 object。 The option to compose dispose method for each handler is not an option.为每个处理程序编写 dispose 方法的选项不是一个选项。

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 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我还有另外7种比较方法

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 .有关如何以及为什么使用http://msdn.microsoft.com/en-us/library/yh598w02(v=VS.100).aspx的完整说明,请参阅此处。 A sample would be一个样本是

using (MyDisposableType disposable1 = GetDisposable1(), disposable2 = GetDisposable2() /*,...*/)
{
    //your actions
}

after exiting from the using block, all disposable objects declared in its header will be disposed.退出using块后,其 header 中声明的所有一次性对象都将被释放。

If your disposable objects are of different types, you can use nested using s:如果您的一次性对象是不同类型的,您可以使用嵌套using s:

using (MyDisposableType1 disposable1 = GetDisposable1())
{
    using (MyDisposableType2 disposable2 = GetDisposable2())
    {
        //more usings if needed, and then your actions
    }
}

I would put the method on an object that impiments idisposible and call this.dispose() in a finally block我会将该方法放在一个object上,该方法是不可处置的,并在 finally 块中调用 this.dispose()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM