2011-08-12 1 views
1

:문제 단순한/깨끗한/다음과 같은 경우에 강력한 형식의 데이터 집합의 Null 값을 처리 할 수있는 가장 쉬운/가장 좋은 방법은 무엇

  • 기본 클래스는 Null 허용을 가지고이 생성자를 통해 설정된 값
  • 파생 클래스의 생성자에는 Strongly Typed DataSet Row가 매개 변수로 사용되며 null 값에 액세스 할 때 예외가 발생합니다.

내가 직면 한 문제를 보여주는 간단한 예제입니다. 코드와의 유사성은 순전히 우연의 일치입니다.

Public MustInherit Class BaseClass 
    Private _Number as Nullable(of integer) 
    Public Sub New(Number as Nullable(of integer)) 
     _Number = Number 
    End Sub 
End Class 

Public Class DerivedClass 
    Inherits BaseClass 

    'Throw System.Data.StrongTypingException "The value for column 'Number' 
    'in table 'SomeData' is DBNull." when Number is null 
    Public Sub New(DataRow as my DataDLL.SomeDataRow) 
      MyBase.New(DataRow.Number) 
    End Sub 

    'First statement of this 'Sub New' must be a call to 'MyBase.New' 
    'or 'MyClass.New' because base class 'BaseClass' of 'DerivedClass' 
    'does not have an accessible 'Sub New' that can be called with no arguments 
    Public Sub New(DataRow as my DataDLL.SomeDataRow) 
     If TermRow.IsNumberNull() Then 
       MyBase.New(Nothing) 
     Else 
       MyBase.New(DataRow.Number) 
     End If 
    End Sub 

    'Also Throw System.Data.StrongTypingException because As part of preparing 
    'the argument list for the call to IIf, the Visual Basic compiler calls 
    'every function in every expression. 
    Public Sub New(DataRow As MyData) 
     MyBase.New(DirectCast(IIf(DataRow.IsNumberNull(), _ 
            Nothing, _ 
            TermRow.Number), Nullable(Of Integer))) 
    End Sub 

End Class 


나는 단지 내가 생각 3 개의 대안을 보여주기 위해 3 Public Sub New을 넣어. 의미가

+0

첫 번째 생성자에서 예외가 발생했습니다. 두 번째 경우에는 첫 번째 줄이어야한다고 말했듯이 모든 논리를 한 줄에 표시하는 방법을 찾아야합니다. VB는 재미 있습니다! – Jay

답변

1

, 당신은 Integer?

대신 IIF과 동일하지 않은, DBNull를 확인해야는 IF Operator, 마녀 .NET 3.5에 새로운 시도. If 함수가 0을 반환하기 때문에 NothingNullable(Of Integer)으로 변환해야합니다. 반환 값의 반환 유형은 true 부분과 false 부분의 on the wider of the types을 기반으로 결정됩니다.

Public Sub New(DataRow As MyData) 
    MyBase.New(If(DataRow.IsNumberNull(), _ 
        DirectCast(Nothing, Nullable(Of Integer)), _ 
        DataRow.Number)) 
End Sub 
+0

OrElse가 생명을 구할 ... – David

+0

.Net 4.0을 사용하고 있습니까? 그렇다면'If (...) '문을 사용할 수 있습니다. – Jay

+0

.NET 3.5에서 'if (...)'문이 도입 된 것처럼 보입니다! 그래서 나는 그것을 사용할 수 있었다. 한편, If는'IsNumberNull'이'true' 일 때'Nothing' 대신'0'을 리턴합니다. 해결 방법은 if ​​문 전체를 캐스팅하는 대신 Nothing을 Nullable (Of Integer)에 캐스트하는 것입니다. 어쨌든, 나는 (다시) 대답을 편집 했으므로 편집을 받아 들여서 어젯밤 중간에 배치 한 현상금에 답하고 받아 들일 것입니다. – DavRob60

관련 문제