Расширяющие и сужающие преобразования (Visual Basic)Widening and Narrowing Conversions (Visual Basic)
Важное замечание при преобразовании типов заключается в том, находится ли результат преобразования в диапазоне целевого типа данных.An important consideration with a type conversion is whether the result of the conversion is within the range of the destination data type.
Расширяющее преобразование изменяет значение на тип данных, который может допускать любое возможное значение исходных данных.A widening conversion changes a value to a data type that can allow for any possible value of the original data. Расширяющие преобразования сохраняют исходное значение, но могут изменять его представление.Widening conversions preserve the source value but can change its representation. Это происходит при преобразовании из целочисленного типа в Decimal
или из Char
в String
.This occurs if you convert from an integral type to Decimal
, or from Char
to String
.
Преобразование сужения изменяет тип данных значения на тип, который не сможет содержать некоторые возможные значения.A narrowing conversion changes a value to a data type that might not be able to hold some of the possible values. Например, дробное значение округляется при преобразовании в целочисленный тип, а числовой тип, преобразуемый в, Boolean
сокращается до либо True
False
.For example, a fractional value is rounded when it is converted to an integral type, and a numeric type being converted to Boolean
is reduced to either True
or False
.
расширяющие преобразованияWidening Conversions
В следующей таблице показаны стандартные расширяющие преобразования.The following table shows the standard widening conversions.
Тип данныхData type | Расширяется до типов данных 1Widens to data types 1 |
---|---|
SByteSByte | SByte , Short , Integer , Long , Decimal , Single , Double SByte , Short , Integer , Long , Decimal , Single , Double |
ByteByte | Byte , Short , UShort , Integer , UInteger , Long , ULong , Decimal , Single , Double Byte , Short , UShort , Integer , UInteger , Long , ULong , Decimal , Single , Double |
ShortShort | Short , Integer , Long , Decimal , Single , Double Short , Integer , Long , Decimal , Single , Double |
UShortUShort | UShort , Integer , UInteger , Long , ULong , Decimal , Single , Double UShort , Integer , UInteger , Long , ULong , Decimal , Single , Double |
Целое числоInteger | Integer ,,, Long Decimal Single , Double 2Integer , Long , Decimal , Single , Double 2 |
UIntegerUInteger | UInteger , Long , ULong , Decimal , Single , Double 2UInteger , Long , ULong , Decimal , Single , Double 2 |
LongLong | Long , Decimal , Single , Double 2Long , Decimal , Single , Double 2 |
ULongULong | ULong , Decimal , Single , Double 2ULong , Decimal , Single , Double 2 |
DecimalDecimal | Decimal , Single , Double 2Decimal , Single , Double 2 |
SingleSingle | Single , Double Single , Double |
DoubleDouble | Double |
Любой перечислимый тип (enum)Any enumerated type (Enum) | Его базовый целочисленный тип и любой тип, к которому расширяется базовый тип.Its underlying integral type and any type to which the underlying type widens. |
CharChar | Char , String Char , String |
Массив Char Char array |
Char inArray String Char array, String |
Любой типAny type | ОбъектObject |
Любой производный типAny derived type | Любой базовый тип, от которого он является производным 3.Any base type from which it is derived 3. |
Любой типAny type | Любой интерфейс, который он реализует.Any interface it implements. |
NothingNothing | Любой тип данных или тип объекта.Any data type or object type. |
1 по определению каждый тип данных расширяется до самого себя.1 By definition, every data type widens to itself.
2 преобразования из Integer
, UInteger
, Long
, ULong
или Decimal
в Single
или Double
могут привести к утрате точности, но никогда не будут иметь потери.2 Conversions from Integer
, UInteger
, Long
, ULong
, or Decimal
to Single
or Double
might result in loss of precision, but never in loss of magnitude. В этом смысле они не приводят к утрате информации.In this sense they do not incur information loss.
3 может показаться удивительно, что преобразование из производного типа в один из его базовых типов является расширяющим.3 It might seem surprising that a conversion from a derived type to one of its base types is widening. Обоснованием является то, что производный тип содержит все члены базового типа, поэтому он является экземпляром базового типа.The justification is that the derived type contains all the members of the base type, so it qualifies as an instance of the base type. В обратном направлении базовый тип не содержит новых элементов, определенных производным типом.In the opposite direction, the base type does not contain any new members defined by the derived type.
Расширяющие преобразования всегда выполняются в период выполнения и никогда не вызывают потери данных.Widening conversions always succeed at run time and never incur data loss. Вы всегда можете выполнять их неявно, независимо от того, устанавливает ли оператор Option строго значение переключателя проверки типа в значение On
или Off
.You can always perform them implicitly, whether the Option Strict Statement sets the type checking switch to On
or to Off
.
сужающие преобразованияNarrowing Conversions
К стандартным сужающим преобразованиям относятся следующие:The standard narrowing conversions include the following:
Обратные направления расширяющих преобразований в предыдущей таблице (за исключением того, что каждый тип расширяется до самого себя)The reverse directions of the widening conversions in the preceding table (except that every type widens to itself)
Преобразования в любом направлении между логическим и любым числовым типомConversions in either direction between Boolean and any numeric type
Преобразования любого числового типа в любой перечислимый тип (
Enum
)Conversions from any numeric type to any enumerated type (Enum
)Преобразования в любом направлении между строкой и любым числовым типом,
Boolean
или датойConversions in either direction between String and any numeric type,Boolean
, or DateПреобразование типа данных или типа объекта в производный от него типConversions from a data type or object type to a type derived from it
Сужающие преобразования не всегда выполняются успешно во время выполнения и могут привести к сбою или потери данных.Narrowing conversions do not always succeed at run time, and can fail or incur data loss. Если целевой тип данных не может получить преобразуемое значение, возникает ошибка.An error occurs if the destination data type cannot receive the value being converted. Например, числовое преобразование может привести к переполнению.For example, a numeric conversion can result in an overflow. Компилятор не позволяет выполнять сужающие преобразования неявно, если только оператор Option строго задает для параметра проверки типа значение Off
.The compiler does not allow you to perform narrowing conversions implicitly unless the Option Strict Statement sets the type checking switch to Off
.
Примечание
Ошибка сужения преобразования подавляется для преобразований из элементов в For Each…Next
коллекции в переменную управления циклом.The narrowing-conversion error is suppressed for conversions from the elements in a For Each…Next
collection to the loop control variable. Дополнительные сведения и примеры см. в подразделе «сужающие преобразования» раздела For Each... Следующий оператор.For more information and examples, see the "Narrowing Conversions" section in For Each...Next Statement.
Когда следует использовать сужающие преобразованияWhen to Use Narrowing Conversions
Если известно, что исходное значение можно преобразовать в целевой тип данных без ошибок или потери данных, используется суженное преобразование.You use a narrowing conversion when you know the source value can be converted to the destination data type without error or data loss. Например, если имеется объект String
, который содержит значение true или false, можно использовать CBool
ключевое слово, чтобы преобразовать его в Boolean
.For example, if you have a String
that you know contains either "True" or "False," you can use the CBool
keyword to convert it to Boolean
.
Исключения во время преобразованияExceptions During Conversion
Поскольку расширяющие преобразования всегда выполняются, они не создают исключения.Because widening conversions always succeed, they do not throw exceptions. Сужающие преобразования, когда они завершаются сбоем, чаще всего вызывают следующие исключения:Narrowing conversions, when they fail, most commonly throw the following exceptions:
InvalidCastException — Если преобразование между двумя типами не определеноInvalidCastException — if no conversion is defined between the two types
OverflowException — (только целочисленные типы), если преобразованное значение слишком велико для целевого типаOverflowException — (integral types only) if the converted value is too large for the target type
Если класс или структура определяет функцию CType , которая будет служить оператором преобразования в этот класс или структуру или из этого класса или структуры, это CType
может вызвать любое исключение, которое оно считается соответствующим.If a class or structure defines a CType Function to serve as a conversion operator to or from that class or structure, that CType
can throw any exception it deems appropriate. Кроме того, это CType
может вызывать функции Visual Basic или методы .NET Framework, которые, в свою очередь, могут вызывать различные исключения.In addition, that CType
might call Visual Basic functions or .NET Framework methods, which in turn could throw a variety of exceptions.
Изменения во время преобразования ссылочного типаChanges During Reference Type Conversions
При преобразовании из ссылочного типа копируется только указатель на значение.A conversion from a reference type copies only the pointer to the value. Само значение не копируется и не изменяется каким-либо образом.The value itself is neither copied nor changed in any way. Единственное, что может изменить, — это тип данных переменной, содержащей указатель.The only thing that can change is the data type of the variable holding the pointer. В следующем примере тип данных преобразуется из производного класса в его базовый класс, но объект, на который теперь указывают обе переменные, не изменяется.In the following example, the data type is converted from the derived class to its base class, but the object that both variables now point to is unchanged.
' Assume class cSquare inherits from class cShape.
Dim shape As cShape
Dim square As cSquare = New cSquare
' The following statement performs a widening
' conversion from a derived class to its base class.
shape = square
См. такжеSee also
- Типы данныхData Types
- Преобразование типов в Visual BasicType Conversions in Visual Basic
- Явные и неявные преобразованияImplicit and Explicit Conversions
- Преобразования значений между строковыми и другими типамиConversions Between Strings and Other Types
- Практическое руководство. Преобразование объекта к другому типу в Visual BasicHow to: Convert an Object to Another Type in Visual Basic
- Преобразования массивовArray Conversions
- Типы данныхData Types
- Type Conversion FunctionsType Conversion Functions