2012-01-25 24 views

回答

6

你不能從構造函數返回任何東西,它在那裏進行初始化。

有一對夫婦的事情可以做,根據不同的情況:

  1. 如果初始化failiure是一個特殊的情況下,拋出一個異常,並使用Try塊捕獲它:

    Public Sub New() 
        '... fail to initialize 
        Throw New ApplicationException("Some problem") 'Or whatever type of exception is appropriate 
    End Sub 
    
  2. 如果失敗了很多,你不能過濾輸入什麼的,使構造Private並在Shared方法構造:

    Public Shared Function CreateMyObject() 
        If someFailure Then 
         Return Nothing 
        End If 
    
        Return New MyObject() 'Or something 
    End Function 
    
+0

我會扔去的辦法。謝謝。 – Bill

0

它有點老派,但你可以有一個設置一個異常處理的LastException屬性:

Public Class Foo 
    Private _LastException As Exception = Nothing 
    Public ReadOnly Property LastException As Exception 
     Get 
      Return _LastException 
     End Get 
    End Property 

    Public Sub New() 
     Try 
      'init 
     Catch ex As Exception 
      _LastException = ex 
     End Try 
    End Sub 
End Class 

這需要你的類創建後檢查LastException,但它是一種選擇?

用法:

Dim foo1 As New Foo 
    If Not foo1.LastException Is Nothing Then 
     'some error occurred 
    Else 
     'carry on 
    End If 
相關問題