2012-01-25 23 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 
相关问题