开发者

How to implement a function that takes a param array (variable number of args) of generic args

开发者 https://www.devze.com 2023-01-14 12:17 出处:网络
I have seen a question here where they implemented a generic dispose method tha开发者_StackOverflow中文版t takes any IDisposable objectand calls dispose on it. I would like to make this such that it c

I have seen a question here where they implemented a generic dispose method tha开发者_StackOverflow中文版t takes any IDisposable object and calls dispose on it. I would like to make this such that it can take variable number of args. However, I do want to restrict the args to be IDisposable at compile time. (This is because some people in my organization will end up calling this method even on non IDisposable objects "Just to be safe" and "it causes no harm")

I have implemented the same in VB like this. How can I make it take multiple args. Note that I do want them to be passed by reference because I am setting the variable to nothing.

Public Sub DisposeObject(Of TDisposable As IDisposable)(ByRef disposableObject As TDisposable)
    If disposableObject IsNot Nothing Then
        disposableObject.Dispose()
        disposableObject = Nothing
    End If
End Sub


In VB you get a method with variable number of arguments with the ParamArray modifier on an array parameter.

Note however that ParamArray parameters must be declared ByVal, and changes to the array have no effect in the calling code. So you can't have both variable number of arguments and ByRef semantics.


Donno VB but in C# you could write:

public void DisposeObjects(params IDisposable[] args)
{
  foreach(IDisposable obj in args)
  {
     if(obj != null)
     {
        obj.Dispose();
     }
  }
}


Here is how you do it:

Public Sub DisposeObject(ByVal ParamArray disposableObjects() As IDisposable)
    For Each obj As IDisposable In disposableObjects
        If Not IsNothing(obj) Then obj.Dispose()
    Next
End Sub

But I do not recommend such a solution. It's much better to use the "using" statement.

In c#

using (var obj = new TypeImlementingIdisposable)
{
   //do stuff with the object here
}

and in vb:

Using obj As New TypeImlementingIdisposable
   ' do stuff with the object here
End Using

This ensures that the objects always are disposed, not matter if an exception is thrown or not.

You can read more at msdn


Public Sub DisposeObjects(Of T As IDisposable)(ByRef disposableObject As T)
    Dim disposable As IDisposable = CType(disposableObject, T)
    disposableObject = CType(Nothing, T)
    If (disposable IsNot Nothing) Then
        disposable.Dispose()
    End If
End Sub

Usage:

Dim any as Foo = New Foo

DisposeObjects(CType(any, Foo))

0

精彩评论

暂无评论...
验证码 换一张
取 消