Partilhar via


Implementação de tipos de dados (Visual Basic)

Every elementary data type in Visual Basic is supported by a structure or a class in the System namespace. The compiler uses each data type keyword as an alias for the underlying structure or class. For example, declaring a variable with the reserved word Byte is the same as declaring it with the fully qualified structure name System.Byte.

Em Visual Basic, tipos de dados são implementados com base na sua classificação. The Visual Basic data types can be classified according to whether a variable of a particular type stores its own data or a pointer to the data. If it stores its own data it is a value type; if it holds a pointer to data elsewhere in memory it is a reference type.

Value Types

A data type is a value type if it holds the data within its own memory allocation. Value types include the following:

  • All numeric data types

  • Boolean, Char, and Date

  • All structures, even if their members are reference types

  • Enumerations, since their underlying type is always SByte, Short, Integer, Long, Byte, UShort, UInteger, or ULong

Cada estrutura é um tipo de valor, mesmo se ele tem o tipo de referência membros. Por esse motivo, o valor tipos como Char e Integer são implementados por .NET Framework estruturas.

Você pode declarar um tipo de valor usando o reservada palavra-chave, por exemplo, Decimal. You can also use the New keyword to initialize a value type. This is especially useful if the type has a constructor that takes parameters. An example of this is the Decimal(Int32, Int32, Int32, Boolean, Byte) constructor, which builds a new Decimal value from the supplied parts.

Reference Types

A reference type contains a pointer to another memory location that holds the data. Reference types include the following:

  • String

  • All arrays, even if their elements are value types

  • Class types, such as Form

  • Delegates

Uma classe é um tipo de referência. Por esse motivo, tipos de referência, como Object e String são suportados pelo .NET Framework classes. Observe que cada array um tipo de referência, mesmo que seus membros são tipos de valor.

Since every reference type represents an underlying .NET Framework class, you must use the operador New (Visual Basic) keyword when you initialize it. The following statement initializes an array.

Dim totals() As Single = New Single(8) {}

Tipos adicionais estão disponíveis no.NET Framework

The common language runtime (CLR) also supports structures and classes that Visual Basic does not supply. For example, the System.Guid structure provides a globally unique identifier (GUID), and the System.TimeZone class supports a time zone. You can use these types to declare variables and constants, and you can access the methods the .NET Framework implements on these types. However, Visual Basic does not support operations or type conversions that involve types it does not supply.

Elements That Are Not Types

The following programming elements do not qualify as types, because you cannot specify any of them as a data type for a declared element:

  • Namespaces

  • Modules

  • Events

  • Properties and procedures

  • Variables, constants, and fields

Working with the Object Data Type

You can assign either a reference type or a value type to a variable of the Object data type. An Object variable always holds a pointer to the data, never the data itself. However, if you assign a value type to an Object variable, it behaves as if it holds its own data. For more information, see Tipo de dados Object.

Você pode descobrir se um Object variável está atuando como um tipo de referência ou um tipo de valor , passando-o para o IsReference método no Information classe a Microsoft.VisualBasic namespace. Information.IsReferenceRetorna True se o conteúdo da Object variável representa um tipo de referência.

Data Types Have Members

Because they are supported by .NET Framework structures and classes, Visual Basic data types have members. These members include constructors, methods, properties, and fields. You can access the members (except the constructors) on a variable the same way you access methods and properties on an object.

The following example uses the Year, Month, and Day properties and the DaysInMonth method of the System.DateTime structure to determine how many days are remaining in the current month.

Dim current As Date = Now
Dim daysRemaining As Integer
daysRemaining = Date.DaysInMonth(current.Year, current.Month) - current.Day

Note that you must qualify a reference to a data type member with either the name of the type (Date) or the name of a variable declared to be of that type (current).

Examples of Data Type Members

The following code prototypes illustrate some of the useful methods, properties, and fields on the data types.

<Char>.IsDigit() ' Returns True if character is a numeric digit.

<Char>.IsLower() ' Returns True if character is a lowercase letter.

<Date>.IsLeapYear() ' Returns True if current year is a leap year.

<Date>.ToUniversalTime() ' Returns local date/time converted to UTC.

<Double>.IsInfinity() ' Returns True if contents represent infinity.

<Double>.IsNaN() ' Returns True if contents are not a number (0/0).

<Long>.MaxValue ' Constant representing largest positive Int64 value.

<Object>.GetType() ' Returns Type object representing type of <Object>.

<Object>.GetType().GetTypeCode() ' Returns type code of <Object>.

<String>.Chars(<index>) ' Character at position <index> of <String>.

<String>.Length ' Number of characters currently in <String>.

All numeric types, including Byte and Char, expose the MaxValue and MinValue public fields, which can be very useful when dealing with these types.

Equivalence of Data Type Members Is Not Assured

The .NET Framework also supplies several methods on data types that might appear to be equivalent to Visual Basic functions and keywords. However, Visual Basic does not always use the .NET Framework methods to accomplish conversion or other operations, and the results are not always identical.

For example, the ToSingle method performs the same type of action as the CSng keyword does on a Decimal expression. But CSng is not guaranteed to use System.dataType.ToSingle, and therefore the results are not guaranteed to be the same under marginal or boundary conditions.

Generally, you should use the Visual Basic programming elements because they are easier to use and make your code more readable. In some cases, additional functionality might be required that is provided by a .NET Framework method. Para obter um exemplo disto, consulte " Resultadode Mod operador oferece não retornar precisas" in Solucionando problemas de tipos de dados (Visual Basic).

Term

Definition

Tipos de dados no Visual Basic

Introduces the Visual Basic data types and describes how to use them.

Resumo de tipo de dados (Visual Basic)

Lists the elementary data types supplied by Visual Basic.

Conversões de Tipo no Visual Basic

Explica a conversão de tipo, o que é o processo de alteração de um valor de um tipo de dados para outro tipo.

Estruturas (Visual Basic)

Explica as estruturas, que são do usuário-definição de tipos são declarados com o Structure palavra-chave.

Uso eficiente de tipos de dados (Visual Basic)

Descreve maneiras de obter a execução mais rápida usando os tipos de dados.

Tipo de dados Object

Descreve o Object tipo de dados, que pode ser usado para se referir a qualquer tipo de dadosde dados.

Reference

Boolean

Byte

Char

DateTime

Decimal

Double

Guid

TimeZone