簡體   English   中英

方法處理功能 C#

[英]Method dispose functionality C#

有沒有辦法在不使用 C# 2010 (.Net 4) 中的 try-finally 塊的情況下處理方法變量?

故事:我的文件處理程序方法很少。 每個處理程序(方法)都可以在執行過程中中止。 我喜歡在退出方法之前處理所有方法的 object。 為每個處理程序編寫 dispose 方法的選項不是一個選項。

謝謝

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
    }
}`

我還有另外7種比較方法

using 有關如何以及為什么使用http://msdn.microsoft.com/en-us/library/yh598w02(v=VS.100).aspx的完整說明,請參閱此處。 一個樣本是

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

退出using塊后,其 header 中聲明的所有一次性對象都將被釋放。

如果您的一次性對象是不同類型的,您可以使用嵌套using s:

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

我會將該方法放在一個object上,該方法是不可處置的,並在 finally 塊中調用 this.dispose()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM