2010-11-03 116 views
1

好吧,所以我有一个类A实现方法M1,需要一个Excel路径和工作表名称,并返回一个OledbDataReader。 B类调用方法M1,用OledbDataReader做一些事情,然后关闭OledbDataReader。但我怎样才能关闭OLEDBConnection对象?我没有访问它,因为A类中的M1打开了连接!有任何想法吗?谢谢你如何关闭oledbconnection对象?

回答

1

可以重塑你这样的A类实现IDisposable

class HelperClass : IDisposable 
{ 
    private bool _disposed; 
    private OleDbConnection _connection; 

    public HelperClass() 
    { 
     _connection = << open the conection >>; 
    } 

    public OledbDataReader GetOpenedReader() 
    { 
     return << open your reader here with the connection >>; 
    } 

    public void Dispose() 
    { 
     if (!_disposed) 
     { 
      _disposed = true; 

      _connection.Dispose(); 
     } 
    } 
} 

然后,它的呼叫班的职责如下:

using (var helperClass = new HelperClass()) 
{ 
    // call the method that opens the reader and uses it 
} 
+0

首先,感谢您的详细解答。我真的很新鲜。我从来没有听说过“助手类之前”。你建议任何好的教程,这将有助于我更好地理解你给我发送的?以及关于您发给我的代码,我将使用它,然后在调用A类方法的B类中,我将首先调用GetOpenerReader,然后调用Dispose方法..对吧? – PeacefulSoul 2010-11-03 18:29:33

+0

在这个例子中,'HelperClass'是类'A'。 'using'的例子为你调用Dispose。如果你使用这样的类,会自动调用Dispose。 – 2010-11-03 19:47:44

1

如果你有像你这样的外部类的使用。

using (OleDbConnection connection = new OleDbConnection(connectionString)) 
{ 



} 

这将出售其所有的好时机......