Generic type checking

前端 未结 8 1419
既然无缘
既然无缘 2020-12-22 17:10

Is there a way to enforce/limit the types that are passed to primitives? (bool, int, string, etc.)

Now, I know you can limit the generic typ

8条回答
  •  独厮守ぢ
    2020-12-22 17:38

    @Rob, Enum's will slip through the TypeValid function as it's TypeCode is Integer. I've updated the function to also check for Enum.

    Private Function TypeValid() As Boolean
        Dim g As Type = GetType(T)
        Dim code As TypeCode = Type.GetTypeCode(g)
    
        ' All of the TypeCode Enumeration refer Primitive Types
        ' with the exception of Object and Empty (Nothing).
        ' Note: must also catch Enum as its type is Integer.
        Select Case code
            Case TypeCode.Object
                Return False
            Case Else
                ' Enum's TypeCode is Integer, so check BaseType
                If g.BaseType Is GetType(System.Enum) Then
                    Return False
                Else
                    Return True
                End If
        End Select
    End Function
    

提交回复
热议问题