代码之家  ›  专栏  ›  技术社区  ›  DevByDefault

如何实现采用泛型参数的param数组(参数的可变数目)的函数

  •  0
  • DevByDefault  · 技术社区  · 14 年前

    我看过一本书 question

    我已经在VB中实现了同样的功能。我怎样才能让它需要多个参数。请注意,我确实希望他们 通过引用传递

    Public Sub DisposeObject(Of TDisposable As IDisposable)(ByRef disposableObject As TDisposable)
        If disposableObject IsNot Nothing Then
            disposableObject.Dispose()
            disposableObject = Nothing
        End If
    End Sub
    
    4 回复  |  直到 7 年前
        1
  •  1
  •   Mattias S    14 年前

    但是请注意,ParamArray参数必须由val声明,对数组的更改对调用代码没有影响。所以不能同时拥有可变数量的参数和ByRef语义。

        2
  •  0
  •   Adrian Zanescu    14 年前

    public void DisposeObjects(params IDisposable[] args)
    {
      foreach(IDisposable obj in args)
      {
         if(obj != null)
         {
            obj.Dispose();
         }
      }
    }
    
        3
  •  0
  •   jgauffin    14 年前

    以下是您的操作方法:

    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
    

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

    在vb中:

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

    这样可以确保对象 总是 不管是否抛出异常,都会释放。

    msdn

        4
  •  0
  •   silver    10 年前
    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
    

    用法:

    Dim any as Foo=新Foo

    处置对象(CType(any,Foo))