Convert.ToByte 方法

定義

將指定的值轉換為 8 位元不帶正負號的整數。

多載

ToByte(String)

將指定之數字的字串表示,轉換為相等的 8 位元不帶正負號的整數。

ToByte(UInt16)

將指定的 16 位元不帶正負號整數的值,轉換為相等的 8 位元不帶正負號整數。

ToByte(UInt32)

將指定的 32 位元不帶正負號整數的值,轉換為相等的 8 位元不帶正負號整數。

ToByte(String, Int32)

將指定基底中數字的字串表示,轉換為相等的 8 位元不帶正負號的整數。

ToByte(Object, IFormatProvider)

使用指定之特定文化特性格式資訊,將指定之物件的值轉換為 8 位元不帶正負號的整數。

ToByte(String, IFormatProvider)

使用指定之特定文化特性格式資訊,將指定之數字的字串表示轉換為相等的 8 位元不帶正負號的整數。

ToByte(Single)

將指定之單精確度浮點數的值,轉換為相等的 8 位元不帶正負號的整數。

ToByte(UInt64)

將指定的 64 位元不帶正負號整數的值,轉換為相等的 8 位元不帶正負號整數。

ToByte(SByte)

將指定的 8 位元帶正負號的整數值轉換為相等的 8 位元不帶正負號的整數。

ToByte(DateTime)

呼叫這個方法一律會擲回 InvalidCastException

ToByte(Int64)

將指定的 64 位元帶正負號的整數值轉換為相等的 8 位元不帶正負號的整數。

ToByte(Byte)

傳回指定的 8 位元不帶正負號整數;不會執行實際的轉換。

ToByte(Char)

將指定的 Unicode 字元值轉換為相等的 8 位元不帶正負號的整數。

ToByte(Decimal)

將指定之十進位數字的值,轉換為相等的 8 位元不帶正負號的整數。

ToByte(Boolean)

將指定的布林值轉換為相等的 8 位元不帶正負號的整數。

ToByte(Int16)

將指定的 16 位元帶正負號的整數值轉換為相等的 8 位元不帶正負號的整數。

ToByte(Int32)

將指定的 32 位元帶正負號的整數值轉換為相等的 8 位元不帶正負號的整數。

ToByte(Double)

將指定之雙精確度浮點數的值,轉換為相等的 8 位元不帶正負號的整數。

ToByte(Object)

將指定之物件的值轉換為 8 位元不帶正負號的整數。

ToByte(String)

將指定之數字的字串表示,轉換為相等的 8 位元不帶正負號的整數。

public:
 static System::Byte ToByte(System::String ^ value);
public static byte ToByte (string value);
public static byte ToByte (string? value);
static member ToByte : string -> byte
Public Shared Function ToByte (value As String) As Byte

參數

value
String

字串,包含要轉換的數字。

傳回

8 位元不帶正負號的整數,等於 value;而若 valuenull,則為零。

例外狀況

value 不是由後面接著一連串數字 (0 到 9) 的任意符號所組成。

value 代表小於 Byte.MinValue 或大於 Byte.MaxValue 的數位。

範例

下列範例會定義字串數位,並嘗試將每個字串 Byte轉換成 。 請注意,當字串剖析為零時 nullString.Empty 會擲回 FormatException。 另請注意,雖然前置和尾端空格已成功剖析,但格式化符號,例如貨幣符號、群組分隔符或小數分隔符,則不會。

using System;

public class Example
{
   public static void Main()
   {
      String[] values = { null, "", "0xC9", "C9", "101", "16.3",
                          "$12", "$12.01", "-4", "1,032", "255",
                          "   16  " };
      foreach (var value in values) {
         try {
            byte number = Convert.ToByte(value);
            Console.WriteLine("'{0}' --> {1}",
                              value == null ? "<null>" : value, number);
         }
         catch (FormatException) {
            Console.WriteLine("Bad Format: '{0}'",
                              value == null ? "<null>" : value);
         }
         catch (OverflowException) {
            Console.WriteLine("OverflowException: '{0}'", value);
         }
      }
   }
}
// The example displays the following output:
//     '<null>' --> 0
//     Bad Format: ''
//     Bad Format: '0xC9'
//     Bad Format: 'C9'
//     '101' --> 101
//     Bad Format: '16.3'
//     Bad Format: '$12'
//     Bad Format: '$12.01'
//     OverflowException: '-4'
//     Bad Format: '1,032'
//     '255' --> 255
//     '   16  ' --> 16
open System

let values = 
    [| null; ""; "0xC9"; "C9"; "101"; "16.3"; "$12"
       "$12.01"; "-4"; "1,032"; "255"; "   16  " |]

for value in values do
    try
        let number = Convert.ToByte(value)
        printfn $"""'%A{value}' --> {number}"""
    with
    | :? FormatException ->
        printfn $"Bad Format: '%A{value}'"
    | :? OverflowException ->
        printfn $"OverflowException: '{value}'"
        
// The example displays the following output:
//     '<null>' --> 0
//     Bad Format: ''
//     Bad Format: '0xC9'
//     Bad Format: 'C9'
//     '101' --> 101
//     Bad Format: '16.3'
//     Bad Format: '$12'
//     Bad Format: '$12.01'
//     OverflowException: '-4'
//     Bad Format: '1,032'
//     '255' --> 255
//     '   16  ' --> 16
Module Example
   Public Sub Main()
      Dim values() As String = { Nothing, "", "0xC9", "C9", "101", 
                                 "16.3", "$12", "$12.01", "-4", 
                                 "1,032", "255", "   16  " }
      For Each value In values
         Try 
            Dim number As Byte = Convert.ToByte(value)
            Console.WriteLine("'{0}' --> {1}", 
                              If(value Is Nothing, "<null>", value), number)
         Catch e As FormatException
            Console.WriteLine("Bad Format: '{0}'", 
                              If(value Is Nothing, "<null>", value))
         Catch e As OverflowException
            Console.WriteLine("OverflowException: '{0}'", value)
         End Try
      Next
   End Sub
End Module
' The example displays the following output:
'     '<null>' --> 0
'     Bad Format: ''
'     Bad Format: '0xC9'
'     Bad Format: 'C9'
'     '101' --> 101
'     Bad Format: '16.3'
'     Bad Format: '$12'
'     Bad Format: '$12.01'
'     OverflowException: '-4'
'     Bad Format: '1,032'
'     '255' --> 255
'     '   16  ' --> 16

備註

ToByte(String)使用方法相當於傳遞valueByte.Parse(String) 方法。 value 使用目前文化特性的格式設定慣例來解譯。

如果您不想在轉換失敗時處理例外狀況,您可以改為呼叫 Byte.TryParse 方法。 它會傳回值 Boolean ,指出轉換成功或失敗。

另請參閱

適用於

ToByte(UInt16)

重要

此 API 不符合 CLS 規範。

將指定的 16 位元不帶正負號整數的值,轉換為相等的 8 位元不帶正負號整數。

public:
 static System::Byte ToByte(System::UInt16 value);
[System.CLSCompliant(false)]
public static byte ToByte (ushort value);
[<System.CLSCompliant(false)>]
static member ToByte : uint16 -> byte
Public Shared Function ToByte (value As UShort) As Byte

參數

value
UInt16

要轉換之 16 位元不帶正負號的整數。

傳回

等於 value 的 8 位元不帶正負號整數。

屬性

例外狀況

範例

下列範例會將不帶正負號的16位整數陣列轉換為 Byte 值。

ushort[] numbers = { UInt16.MinValue, 121, 340, UInt16.MaxValue };
byte result;
foreach (ushort number in numbers)
{
   try {
      result = Convert.ToByte(number);
      Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.",
                        number.GetType().Name, number,
                        result.GetType().Name, result);
   }
   catch (OverflowException) {
      Console.WriteLine("The {0} value {1} is outside the range of the Byte type.",
                        number.GetType().Name, number);
   }
}
// The example displays the following output:
//       Converted the UInt16 value 0 to the Byte value 0.
//       Converted the UInt16 value 121 to the Byte value 121.
//       The UInt16 value 340 is outside the range of the Byte type.
//       The UInt16 value 65535 is outside the range of the Byte type.
let numbers = [| UInt16.MinValue; 121us; 340us; UInt16.MaxValue |]
for number in numbers do
    try
        let result = Convert.ToByte number
        printfn $"Converted the {number.GetType().Name} value {number} to the {result.GetType().Name} value {result}."
    with :? OverflowException ->
        printfn $"The {number.GetType().Name} value {number} is outside the range of the Byte type."
// The example displays the following output:
//       Converted the UInt16 value 0 to the Byte value 0.
//       Converted the UInt16 value 121 to the Byte value 121.
//       The UInt16 value 340 is outside the range of the Byte type.
//       The UInt16 value 65535 is outside the range of the Byte type.
Dim numbers() As UShort = { UInt16.MinValue, 121, 340, UInt16.MaxValue }
Dim result As Byte
For Each number As UShort In numbers
   Try
      result = Convert.ToByte(number)
      Console.WriteLIne("Converted the {0} value {1} to the {2} value {3}.", _
                        number.GetType().Name, number, _
                        result.GetType().Name, result)
   Catch e As OverflowException
      Console.WriteLine("The {0} value {1} is outside the range of the Byte type.", _
                        number.GetType().Name, number)
   End Try
Next
' The example displays the following output:
'       Converted the UInt16 value 0 to the Byte value 0.
'       Converted the UInt16 value 121 to the Byte value 121.
'       The UInt16 value 340 is outside the range of the Byte type.
'       The UInt16 value 65535 is outside the range of the Byte type.

適用於

ToByte(UInt32)

重要

此 API 不符合 CLS 規範。

將指定的 32 位元不帶正負號整數的值,轉換為相等的 8 位元不帶正負號整數。

public:
 static System::Byte ToByte(System::UInt32 value);
[System.CLSCompliant(false)]
public static byte ToByte (uint value);
[<System.CLSCompliant(false)>]
static member ToByte : uint32 -> byte
Public Shared Function ToByte (value As UInteger) As Byte

參數

value
UInt32

要轉換之 32 位元不帶正負號的整數。

傳回

等於 value 的 8 位元不帶正負號整數。

屬性

例外狀況

範例

下列範例會將不帶正負號整數的陣列轉換成 Byte 值。

uint[] numbers = { UInt32.MinValue, 121, 340, UInt32.MaxValue };
byte result;
foreach (uint number in numbers)
{
   try {
      result = Convert.ToByte(number);
      Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.",
                        number.GetType().Name, number,
                        result.GetType().Name, result);
   }
   catch (OverflowException) {
      Console.WriteLine("The {0} value {1} is outside the range of the Byte type.",
                        number.GetType().Name, number);
   }
}
// The example displays the following output:
//       Converted the UInt32 value 0 to the Byte value 0.
//       Converted the UInt32 value 121 to the Byte value 121.
//       The UInt32 value 340 is outside the range of the Byte type.
//       The UInt32 value 4294967295 is outside the range of the Byte type.
let numbers = [| UInt32.MinValue; 121u; 340u; UInt32.MaxValue |]
for number in numbers do
    try
        let result = Convert.ToByte number
        printfn $"Converted the {number.GetType().Name} value {number} to the {result.GetType().Name} value {result}."
    with :? OverflowException ->
        printfn $"The {number.GetType().Name} value {number} is outside the range of the Byte type."
// The example displays the following output:
//       Converted the UInt32 value 0 to the Byte value 0.
//       Converted the UInt32 value 121 to the Byte value 121.
//       The UInt32 value 340 is outside the range of the Byte type.
//       The UInt32 value 4294967295 is outside the range of the Byte type.
Dim numbers() As UInteger = { UInt32.MinValue, 121, 340, UInt32.MaxValue }
Dim result As Byte
For Each number As UInteger In numbers
   Try
      result = Convert.ToByte(number)
      Console.WriteLIne("Converted the {0} value {1} to the {2} value {3}.", _
                        number.GetType().Name, number, _
                        result.GetType().Name, result)
   Catch e As OverflowException
      Console.WriteLine("The {0} value {1} is outside the range of the Byte type.", _
                        number.GetType().Name, number)
   End Try
Next
' The example displays the following output:
'       Converted the UInt32 value 0 to the Byte value 0.
'       Converted the UInt32 value 121 to the Byte value 121.
'       The UInt32 value 340 is outside the range of the Byte type.
'       The UInt32 value 4294967295 is outside the range of the Byte type.

適用於

ToByte(String, Int32)

將指定基底中數字的字串表示,轉換為相等的 8 位元不帶正負號的整數。

public:
 static System::Byte ToByte(System::String ^ value, int fromBase);
public static byte ToByte (string value, int fromBase);
public static byte ToByte (string? value, int fromBase);
static member ToByte : string * int -> byte
Public Shared Function ToByte (value As String, fromBase As Integer) As Byte

參數

value
String

字串,包含要轉換的數字。

fromBase
Int32

value 中數字的基底,必須是 2、8、10 或 16。

傳回

value 中之數字相等的 8 位元不帶正負號的整數;如果 valuenull,則為 0 (零)。

例外狀況

fromBase 不是 2、8、10 或 16。

-或-

代表非基底 10 不帶正負號數字的value,前面會加上負號。

value 所包含的字元在 fromBase 指定的基底中不是有效數字。 如果 value 中的第一個字元無效,例外狀況訊息會指出沒有數字可進行轉換;否則訊息會指出 value 包含無效的尾端字元。

代表 10 進位不帶正負號數字的 value,有前置負號。

-或-

value 代表小於 Byte.MinValue 或大於 Byte.MaxValue 的數位。

範例

下列範例會嘗試將字串數位解譯為二進位、八進位、十六進位和十六進位值的表示法。

using System;

public class Example
{
   public static void Main()
   {
      int[] bases = { 2, 8, 10, 16 };
      string[] values = { "-1", "1", "08", "0F", "11" , "12", "30",
                          "101", "255", "FF", "10000000", "80" };
      byte number;
      foreach (int numBase in bases)
      {
         Console.WriteLine("Base {0}:", numBase);
         foreach (string value in values)
         {
            try {
               number = Convert.ToByte(value, numBase);
               Console.WriteLine("   Converted '{0}' to {1}.", value, number);
            }
            catch (FormatException) {
               Console.WriteLine("   '{0}' is not in the correct format for a base {1} byte value.",
                                 value, numBase);
            }
            catch (OverflowException) {
               Console.WriteLine("   '{0}' is outside the range of the Byte type.", value);
            }
            catch (ArgumentException) {
               Console.WriteLine("   '{0}' is invalid in base {1}.", value, numBase);
            }
         }
      }
   }
}
// The example displays the following output:
//    Base 2:
//       '-1' is invalid in base 2.
//       Converted '1' to 1.
//       '08' is not in the correct format for a base 2 conversion.
//       '0F' is not in the correct format for a base 2 conversion.
//       Converted '11' to 3.
//       '12' is not in the correct format for a base 2 conversion.
//       '30' is not in the correct format for a base 2 conversion.
//       Converted '101' to 5.
//       '255' is not in the correct format for a base 2 conversion.
//       'FF' is not in the correct format for a base 2 conversion.
//       Converted '10000000' to 128.
//       '80' is not in the correct format for a base 2 conversion.
//    Base 8:
//       '-1' is invalid in base 8.
//       Converted '1' to 1.
//       '08' is not in the correct format for a base 8 conversion.
//       '0F' is not in the correct format for a base 8 conversion.
//       Converted '11' to 9.
//       Converted '12' to 10.
//       Converted '30' to 24.
//       Converted '101' to 65.
//       Converted '255' to 173.
//       'FF' is not in the correct format for a base 8 conversion.
//       '10000000' is outside the range of the Byte type.
//       '80' is not in the correct format for a base 8 conversion.
//    Base 10:
//       '-1' is outside the range of the Byte type.
//       Converted '1' to 1.
//       Converted '08' to 8.
//       '0F' is not in the correct format for a base 10 conversion.
//       Converted '11' to 11.
//       Converted '12' to 12.
//       Converted '30' to 30.
//       Converted '101' to 101.
//       Converted '255' to 255.
//       'FF' is not in the correct format for a base 10 conversion.
//       '10000000' is outside the range of the Byte type.
//       Converted '80' to 80.
//    Base 16:
//       '-1' is invalid in base 16.
//       Converted '1' to 1.
//       Converted '08' to 8.
//       Converted '0F' to 15.
//       Converted '11' to 17.
//       Converted '12' to 18.
//       Converted '30' to 48.
//       '101' is outside the range of the Byte type.
//       '255' is outside the range of the Byte type.
//       Converted 'FF' to 255.
//       '10000000' is outside the range of the Byte type.
//       Converted '80' to 128.
open System

let bases = [ 2; 8; 10; 16 ]
let values = 
    [| "-1"; "1"; "08"; "0F"; "11"; "12"; "30"
       "101"; "255"; "FF"; "10000000"; "80" |]

for numBase in bases do
    printfn $"Base {numBase}:"
    for value in values do
        try
            let number = Convert.ToByte(value, numBase)
            printfn $"   Converted '{value}' to {number}."
        with
        | :? FormatException ->
            printfn $"   '{value}' is not in the correct format for a base {numBase} byte value."
        | :? OverflowException ->
            printfn $"   '{value}' is outside the range of the Byte type."
        | :? ArgumentException ->
            printfn $"   '{value}' is invalid in base {numBase}."

// The example displays the following output:
//    Base 2:
//       '-1' is invalid in base 2.
//       Converted '1' to 1.
//       '08' is not in the correct format for a base 2 conversion.
//       '0F' is not in the correct format for a base 2 conversion.
//       Converted '11' to 3.
//       '12' is not in the correct format for a base 2 conversion.
//       '30' is not in the correct format for a base 2 conversion.
//       Converted '101' to 5.
//       '255' is not in the correct format for a base 2 conversion.
//       'FF' is not in the correct format for a base 2 conversion.
//       Converted '10000000' to 128.
//       '80' is not in the correct format for a base 2 conversion.
//    Base 8:
//       '-1' is invalid in base 8.
//       Converted '1' to 1.
//       '08' is not in the correct format for a base 8 conversion.
//       '0F' is not in the correct format for a base 8 conversion.
//       Converted '11' to 9.
//       Converted '12' to 10.
//       Converted '30' to 24.
//       Converted '101' to 65.
//       Converted '255' to 173.
//       'FF' is not in the correct format for a base 8 conversion.
//       '10000000' is outside the range of the Byte type.
//       '80' is not in the correct format for a base 8 conversion.
//    Base 10:
//       '-1' is outside the range of the Byte type.
//       Converted '1' to 1.
//       Converted '08' to 8.
//       '0F' is not in the correct format for a base 10 conversion.
//       Converted '11' to 11.
//       Converted '12' to 12.
//       Converted '30' to 30.
//       Converted '101' to 101.
//       Converted '255' to 255.
//       'FF' is not in the correct format for a base 10 conversion.
//       '10000000' is outside the range of the Byte type.
//       Converted '80' to 80.
//    Base 16:
//       '-1' is invalid in base 16.
//       Converted '1' to 1.
//       Converted '08' to 8.
//       Converted '0F' to 15.
//       Converted '11' to 17.
//       Converted '12' to 18.
//       Converted '30' to 48.
//       '101' is outside the range of the Byte type.
//       '255' is outside the range of the Byte type.
//       Converted 'FF' to 255.
//       '10000000' is outside the range of the Byte type.
//       Converted '80' to 128.
Module Example
   Public Sub Main()
      Dim bases() As Integer = { 2, 8, 10, 16 }
      Dim values() As String = { "-1", "1", "08", "0F", "11" , "12", "30", _                
                                  "101", "255", "FF", "10000000", "80" }
      Dim number As Byte
      For Each base As Integer In bases
         Console.WriteLine("Base {0}:", base)
         For Each value As String In values
            Try
               number = Convert.ToByte(value, base)
               Console.WriteLine("   Converted '{0}' to {1}.", value, number)
            Catch e As FormatException
               Console.WriteLine("   '{0}' is not in the correct format for a base {1} conversion.", _
                                 value, base)
            Catch e As OverflowException
               Console.WriteLine("   '{0}' is outside the range of the Byte type.", value)
            Catch e As ArgumentException
               Console.WriteLine("   '{0}' is invalid in base {1}.", value, base)
            End Try   
         Next                                 
      Next 
   End Sub
End Module
' The example displays the following output:
'    Base 2:
'       '-1' is invalid in base 2.
'       Converted '1' to 1.
'       '08' is not in the correct format for a base 2 conversion.
'       '0F' is not in the correct format for a base 2 conversion.
'       Converted '11' to 3.
'       '12' is not in the correct format for a base 2 conversion.
'       '30' is not in the correct format for a base 2 conversion.
'       Converted '101' to 5.
'       '255' is not in the correct format for a base 2 conversion.
'       'FF' is not in the correct format for a base 2 conversion.
'       Converted '10000000' to 128.
'       '80' is not in the correct format for a base 2 conversion.
'    Base 8:
'       '-1' is invalid in base 8.
'       Converted '1' to 1.
'       '08' is not in the correct format for a base 8 conversion.
'       '0F' is not in the correct format for a base 8 conversion.
'       Converted '11' to 9.
'       Converted '12' to 10.
'       Converted '30' to 24.
'       Converted '101' to 65.
'       Converted '255' to 173.
'       'FF' is not in the correct format for a base 8 conversion.
'       '10000000' is outside the range of the Byte type.
'       '80' is not in the correct format for a base 8 conversion.
'    Base 10:
'       '-1' is outside the range of the Byte type.
'       Converted '1' to 1.
'       Converted '08' to 8.
'       '0F' is not in the correct format for a base 10 conversion.
'       Converted '11' to 11.
'       Converted '12' to 12.
'       Converted '30' to 30.
'       Converted '101' to 101.
'       Converted '255' to 255.
'       'FF' is not in the correct format for a base 10 conversion.
'       '10000000' is outside the range of the Byte type.
'       Converted '80' to 80.
'    Base 16:
'       '-1' is invalid in base 16.
'       Converted '1' to 1.
'       Converted '08' to 8.
'       Converted '0F' to 15.
'       Converted '11' to 17.
'       Converted '12' to 18.
'       Converted '30' to 48.
'       '101' is outside the range of the Byte type.
'       '255' is outside the range of the Byte type.
'       Converted 'FF' to 255.
'       '10000000' is outside the range of the Byte type.
'       Converted '80' to 128.

備註

如果 fromBase 為 16,您可以在 參數指定的 value 數位前面加上 “0x” 或 “0X”。

Byte因為數據類型只支援不帶正負號的值,所以ToByte(String, Int32)方法會value假設使用不帶正負號的二進位表示表示法來表示。 換句話說,所有八個位都用來表示數值,而符號位不存在。 因此,可以撰寫程序代碼,其中超出數據類型範圍的 Byte 帶正負號位元組值會轉換成 Byte 值,而不會擲回例外狀況的方法。 下列範例會 MinValue 轉換成其十六進位字串表示,然後呼叫 ToByte(String, Int32) 方法。 方法不會擲回例外狀況,而是顯示訊息:「0x80轉換成 128」。

// Create a hexadecimal value out of range of the Byte type.
string value = SByte.MinValue.ToString("X");
// Convert it back to a number.
try
{
   byte number = Convert.ToByte(value, 16);
   Console.WriteLine("0x{0} converts to {1}.", value, number);
}
catch (OverflowException)
{
   Console.WriteLine("Unable to convert '0x{0}' to a byte.", value);
}
// Create a hexadecimal value out of range of the Byte type.
let value = SByte.MinValue.ToString "X"
// Convert it back to a number.
try
    let number = Convert.ToByte(value, 16)
    printfn $"0x{value} converts to {number}."
with :? OverflowException ->
    printfn $"Unable to convert '0x{value}' to a byte."
' Create a hexadecimal value out of range of the Byte type.
Dim value As String = SByte.MinValue.ToString("X")
' Convert it back to a number.
Try
   Dim number As Byte = Convert.ToByte(value, 16)
   Console.WriteLine("0x{0} converts to {1}.", value, number)
Catch e As OverflowException
   Console.WriteLine("Unable to convert '0x{0}' to a byte.", value)
End Try

執行二進位運算或數值轉換時,開發人員一律會負責確認方法或運算元是否使用適當的數值表示法來解譯特定值。 下列範例說明一種技術,可確保方法在將十六進位字串表示轉換成值時,不會不當使用不帶正負號的二進位表示 Byte 法。 此範例會判斷值是否代表帶正負號或不帶正負號的整數,同時該值將該值轉換成其字串表示。 當範例將值轉換成值 Byte 時,它會檢查原始值是否為帶正負號的整數。 如果是,而且如果設定其高序位 (,表示此值為負數,而且它會使用兩個補碼,而不是不帶正負號的二進位表示法) ,則方法會擲回例外狀況。

// Create a negative hexadecimal value out of range of the Byte type.
sbyte sourceNumber = SByte.MinValue;
bool isSigned = Math.Sign((sbyte)sourceNumber.GetType().GetField("MinValue").GetValue(null)) == -1;
string value = sourceNumber.ToString("X");
byte targetNumber;
try
{
   targetNumber = Convert.ToByte(value, 16);
   if (isSigned && ((targetNumber & 0x80) != 0))
      throw new OverflowException();
   else
      Console.WriteLine("0x{0} converts to {1}.", value, targetNumber);
}
catch (OverflowException)
{
   Console.WriteLine("Unable to convert '0x{0}' to an unsigned byte.", value);
}
// Displays the following to the console:
//    Unable to convert '0x80' to an unsigned byte.
// Create a negative hexadecimal value out of range of the Byte type.
let sourceNumber = SByte.MinValue
let isSigned = sign (sourceNumber.GetType().GetField("MinValue").GetValue null :?> int8) = -1
let value = sourceNumber.ToString "X"
try
    let targetNumber = Convert.ToByte(value, 16)
    if isSigned && targetNumber &&& 0x80uy <> 0uy then
        raise (OverflowException())
    else
        printfn $"0x{value} converts to {targetNumber}."
with :? OverflowException ->
    printfn $"Unable to convert '0x{value}' to an unsigned byte."
// Displays the following to the console:
//    Unable to convert '0x80' to an unsigned byte.
' Create a negative hexadecimal value out of range of the Byte type.
Dim sourceNumber As SByte = SByte.MinValue
Dim isSigned As Boolean = Math.Sign(sourceNumber.MinValue) = -1
Dim value As String = sourceNumber.ToString("X")
Dim targetNumber As Byte
Try
   targetNumber = Convert.ToByte(value, 16)
   If isSigned And ((targetNumber And &H80) <> 0) Then
      Throw New OverflowException()
   Else 
      Console.WriteLine("0x{0} converts to {1}.", value, targetNumber)
   End If    
Catch e As OverflowException
   Console.WriteLine("Unable to convert '0x{0}' to an unsigned byte.", value)
End Try 
' Displays the following to the console:
'    Unable to convert '0x80' to an unsigned byte.

適用於

ToByte(Object, IFormatProvider)

使用指定之特定文化特性格式資訊,將指定之物件的值轉換為 8 位元不帶正負號的整數。

public:
 static System::Byte ToByte(System::Object ^ value, IFormatProvider ^ provider);
public static byte ToByte (object value, IFormatProvider provider);
public static byte ToByte (object? value, IFormatProvider? provider);
static member ToByte : obj * IFormatProvider -> byte
Public Shared Function ToByte (value As Object, provider As IFormatProvider) As Byte

參數

value
Object

實作 IConvertible 介面的物件。

provider
IFormatProvider

物件,提供特定文化特性格式資訊。

傳回

8 位元不帶正負號的整數,等於 value;而若 valuenull,則為零。

例外狀況

value 的屬性格式不適用於 Byte 值。

value 未實作 IConvertible

-或-

不支援從 value 轉換至 Byte 類型。

value 代表小於 Byte.MinValue 或大於 Byte.MaxValue 的數位。

範例

下列範例定義一個實作 ByteString 介面的 IConvertible 類別。 類別會儲存位元組值的字串表示以及符號欄位,以便同時代表帶正負號和不帶正負號的位元組值。

using System;
using System.Globalization;

public enum SignBit { Negative=-1, Zero=0, Positive=1 };

public struct ByteString : IConvertible
{
   private SignBit signBit;
   private string byteString;

   public SignBit Sign
   {
      set { signBit = value; }
      get { return signBit; }
   }

   public string Value
   {
      set {
         if (value.Trim().Length > 2)
            throw new ArgumentException("The string representation of a byte cannot have more than two characters.");
         else
            byteString = value;
      }
      get { return byteString; }
   }

   // IConvertible implementations.
   public TypeCode GetTypeCode() {
      return TypeCode.Object;
   }

   public bool ToBoolean(IFormatProvider provider)
   {
      if (signBit == SignBit.Zero)
         return false;
      else
         return true;
   }

   public byte ToByte(IFormatProvider provider)
   {
      if (signBit == SignBit.Negative)
         throw new OverflowException(String.Format("{0} is out of range of the Byte type.", Convert.ToSByte(byteString, 16)));
      else
         return Byte.Parse(byteString, NumberStyles.HexNumber);
   }

   public char ToChar(IFormatProvider provider)
   {
      if (signBit == SignBit.Negative) {
         throw new OverflowException(String.Format("{0} is out of range of the Char type.", Convert.ToSByte(byteString, 16)));
      }
      else {
         byte byteValue = Byte.Parse(this.byteString, NumberStyles.HexNumber);
         return Convert.ToChar(byteValue);
      }
   }

   public DateTime ToDateTime(IFormatProvider provider)
   {
      throw new InvalidCastException("ByteString to DateTime conversion is not supported.");
   }

   public decimal ToDecimal(IFormatProvider provider)
   {
      if (signBit == SignBit.Negative)
      {
         sbyte byteValue = SByte.Parse(byteString, NumberStyles.HexNumber);
         return Convert.ToDecimal(byteValue);
      }
      else
      {
         byte byteValue = Byte.Parse(byteString, NumberStyles.HexNumber);
         return Convert.ToDecimal(byteValue);
      }
   }

   public double ToDouble(IFormatProvider provider)
   {
      if (signBit == SignBit.Negative)
         return Convert.ToDouble(SByte.Parse(byteString, NumberStyles.HexNumber));
      else
         return Convert.ToDouble(Byte.Parse(byteString, NumberStyles.HexNumber));
   }

   public short ToInt16(IFormatProvider provider)
   {
      if (signBit == SignBit.Negative)
         return Convert.ToInt16(SByte.Parse(byteString, NumberStyles.HexNumber));
      else
         return Convert.ToInt16(Byte.Parse(byteString, NumberStyles.HexNumber));
   }

   public int ToInt32(IFormatProvider provider)
   {
      if (signBit == SignBit.Negative)
         return Convert.ToInt32(SByte.Parse(byteString, NumberStyles.HexNumber));
      else
         return Convert.ToInt32(Byte.Parse(byteString, NumberStyles.HexNumber));
   }

   public long ToInt64(IFormatProvider provider)
   {
      if (signBit == SignBit.Negative)
         return Convert.ToInt64(SByte.Parse(byteString, NumberStyles.HexNumber));
      else
         return Convert.ToInt64(Byte.Parse(byteString, NumberStyles.HexNumber));
   }

   public sbyte ToSByte(IFormatProvider provider)
   {
      if (signBit == SignBit.Negative)
         try {
            return Convert.ToSByte(Byte.Parse(byteString, NumberStyles.HexNumber));
         }
         catch (OverflowException e) {
            throw new OverflowException(String.Format("{0} is outside the range of the SByte type.",
                                                   Byte.Parse(byteString, NumberStyles.HexNumber)), e);
         }
      else
         return SByte.Parse(byteString, NumberStyles.HexNumber);
   }

   public float ToSingle(IFormatProvider provider)
   {
      if (signBit == SignBit.Negative)
         return Convert.ToSingle(SByte.Parse(byteString, NumberStyles.HexNumber));
      else
         return Convert.ToSingle(Byte.Parse(byteString, NumberStyles.HexNumber));
   }

   public string ToString(IFormatProvider provider)
   {
      return "0x" + this.byteString;
   }

   public object ToType(Type conversionType, IFormatProvider provider)
   {
      switch (Type.GetTypeCode(conversionType))
      {
         case TypeCode.Boolean:
            return this.ToBoolean(null);
         case TypeCode.Byte:
            return this.ToByte(null);
         case TypeCode.Char:
            return this.ToChar(null);
         case TypeCode.DateTime:
            return this.ToDateTime(null);
         case TypeCode.Decimal:
            return this.ToDecimal(null);
         case TypeCode.Double:
            return this.ToDouble(null);
         case TypeCode.Int16:
            return this.ToInt16(null);
         case TypeCode.Int32:
            return this.ToInt32(null);
         case TypeCode.Int64:
            return this.ToInt64(null);
         case TypeCode.Object:
            if (typeof(ByteString).Equals(conversionType))
               return this;
            else
               throw new InvalidCastException(String.Format("Conversion to a {0} is not supported.", conversionType.Name));
         case TypeCode.SByte:
            return this.ToSByte(null);
         case TypeCode.Single:
            return this.ToSingle(null);
         case TypeCode.String:
            return this.ToString(null);
         case TypeCode.UInt16:
            return this.ToUInt16(null);
         case TypeCode.UInt32:
            return this.ToUInt32(null);
         case TypeCode.UInt64:
            return this.ToUInt64(null);
         default:
            throw new InvalidCastException(String.Format("Conversion to {0} is not supported.", conversionType.Name));
      }
   }

   public UInt16 ToUInt16(IFormatProvider provider)
   {
      if (signBit == SignBit.Negative)
         throw new OverflowException(String.Format("{0} is outside the range of the UInt16 type.",
                                                   SByte.Parse(byteString, NumberStyles.HexNumber)));
      else
         return Convert.ToUInt16(Byte.Parse(byteString, NumberStyles.HexNumber));
   }

   public UInt32 ToUInt32(IFormatProvider provider)
   {
      if (signBit == SignBit.Negative)
         throw new OverflowException(String.Format("{0} is outside the range of the UInt32 type.",
                                                   SByte.Parse(byteString, NumberStyles.HexNumber)));
      else
         return Convert.ToUInt32(Byte.Parse(byteString, NumberStyles.HexNumber));
   }

   public UInt64 ToUInt64(IFormatProvider provider)
   {
      if (signBit == SignBit.Negative)
         throw new OverflowException(String.Format("{0} is outside the range of the UInt64 type.",
                                                   SByte.Parse(byteString, NumberStyles.HexNumber)));
      else
         return Convert.ToUInt64(Byte.Parse(byteString, NumberStyles.HexNumber));
   }
}
open System
open System.Globalization

type SignBit =
   | Negative = -1
   | Zero = 0
   | Positive = 1

[<Struct>]
type ByteString =
    val mutable private value: string
    
    val mutable Sign : SignBit
    member this.Value
        with get () = this.value
        and set (value: string) =
            if value.Trim().Length > 2 then
                invalidArg "value" "The string representation of a byte cannot have more than two characters"
            else
                this.value <- value 

    // IConvertible implementations.
    interface IConvertible with
        member _.GetTypeCode() =
            TypeCode.Object

        member this.ToBoolean(provider: IFormatProvider) =
            this.Sign <> SignBit.Zero

        member this.ToByte(provider: IFormatProvider) =
            if this.Sign = SignBit.Negative then
                raise (OverflowException $"{Convert.ToSByte(this.value, 16)} is out of range of the Byte type.")
            else
                Byte.Parse(this.value, NumberStyles.HexNumber)

        member this.ToChar(provider: IFormatProvider) =
            if this.Sign = SignBit.Negative then
                raise (OverflowException $"{Convert.ToSByte(this.value, 16)} is out of range of the Char type.")
            else
                let byteValue = Byte.Parse(this.value, NumberStyles.HexNumber)
                Convert.ToChar byteValue

        member _.ToDateTime(provider: IFormatProvider) =
            raise (InvalidCastException "ByteString to DateTime conversion is not supported.")

        member this.ToDecimal(provider: IFormatProvider) =
            if this.Sign = SignBit.Negative then
                let byteValue = SByte.Parse(this.Value, NumberStyles.HexNumber)
                Convert.ToDecimal byteValue
            else
                let byteValue = Byte.Parse(this.Value, NumberStyles.HexNumber)
                Convert.ToDecimal byteValue

        member this.ToDouble(provider: IFormatProvider) =
            if this.Sign = SignBit.Negative then
                Convert.ToDouble(SByte.Parse(this.value, NumberStyles.HexNumber))
            else
                Convert.ToDouble(Byte.Parse(this.value, NumberStyles.HexNumber))

        member this.ToInt16(provider: IFormatProvider) =
            if this.Sign = SignBit.Negative then
                Convert.ToInt16(SByte.Parse(this.value, NumberStyles.HexNumber))
            else
                Convert.ToInt16(Byte.Parse(this.value, NumberStyles.HexNumber))

        member this.ToInt32(provider: IFormatProvider) =
            if this.Sign = SignBit.Negative then
                Convert.ToInt32(SByte.Parse(this.value, NumberStyles.HexNumber))
            else
                Convert.ToInt32(Byte.Parse(this.value, NumberStyles.HexNumber))

        member this.ToInt64(provider: IFormatProvider) =
            if this.Sign = SignBit.Negative then
                Convert.ToInt64(SByte.Parse(this.value, NumberStyles.HexNumber))
            else
                Convert.ToInt64(Byte.Parse(this.value, NumberStyles.HexNumber))

        member this.ToSByte(provider: IFormatProvider) =
            if this.Sign = SignBit.Negative then
                try
                    Convert.ToSByte(Byte.Parse(this.value, NumberStyles.HexNumber))
                with :? OverflowException as e ->
                    raise (OverflowException($"{Byte.Parse(this.value, NumberStyles.HexNumber)} is outside the range of the SByte type.", e))
            else
                SByte.Parse(this.value, NumberStyles.HexNumber)

        member this.ToSingle(provider: IFormatProvider) =
            if this.Sign = SignBit.Negative then
                Convert.ToSingle(SByte.Parse(this.value, NumberStyles.HexNumber))
            else
                Convert.ToSingle(Byte.Parse(this.value, NumberStyles.HexNumber))

        member this.ToString(provider: IFormatProvider) =
            "0x" + this.value

        member this.ToType(conversionType: Type, provider: IFormatProvider): obj =
            let this = this :> IConvertible
            match Type.GetTypeCode conversionType with
            | TypeCode.Boolean ->
                this.ToBoolean null
            | TypeCode.Byte ->
                this.ToByte null
            | TypeCode.Char ->
                this.ToChar null
            | TypeCode.DateTime ->
                this.ToDateTime null
            | TypeCode.Decimal ->
                this.ToDecimal null
            | TypeCode.Double ->
                this.ToDouble null
            | TypeCode.Int16 ->
                this.ToInt16 null
            | TypeCode.Int32 ->
                this.ToInt32 null
            | TypeCode.Int64 ->
                this.ToInt64 null
            | TypeCode.Object ->
                if typeof<ByteString>.Equals conversionType then
                    this
                else
                    raise (InvalidCastException $"Conversion to a {conversionType.Name} is not supported.")
            | TypeCode.SByte ->
                this.ToSByte null
            | TypeCode.Single ->
                this.ToSingle null
            | TypeCode.String ->
                this.ToString null
            | TypeCode.UInt16 ->
                this.ToUInt16 null
            | TypeCode.UInt32 ->
                this.ToUInt32 null
            | TypeCode.UInt64 ->
                this.ToUInt64 null
            | _ ->
                raise (InvalidCastException $"Conversion to {conversionType.Name} is not supported.")

        member this.ToUInt16(provider: IFormatProvider) =
            if this.Sign = SignBit.Negative then
                raise (OverflowException $"{SByte.Parse(this.value, NumberStyles.HexNumber)} is outside the range of the UInt16 type.")
            else
                Convert.ToUInt16(Byte.Parse(this.value, NumberStyles.HexNumber))

        member this.ToUInt32(provider: IFormatProvider) =
            if this.Sign = SignBit.Negative then
                raise (OverflowException $"{SByte.Parse(this.value, NumberStyles.HexNumber)} is outside the range of the UInt32 type.")
            else
                Convert.ToUInt32(Byte.Parse(this.value, NumberStyles.HexNumber))

        member this.ToUInt64(provider: IFormatProvider) =
            if this.Sign = SignBit.Negative then
                raise (OverflowException $"{SByte.Parse(this.value, NumberStyles.HexNumber)} is outside the range of the UInt64 type.")
            else
                Convert.ToUInt64(Byte.Parse(this.value, NumberStyles.HexNumber))
Imports System.Globalization

Public Enum SignBit As Integer
   Positive = 1
   Zero = 0
   Negative = -1
End Enum

Public Structure ByteString : Implements IConvertible
   Private signBit As SignBit
   Private byteString As String
   
   Public Property Sign As SignBit
      Set
         signBit = value
      End Set
      Get
         Return signBit
      End Get
   End Property
   
   Public Property Value As String
      Set
         If value.Trim().Length > 2 Then
            Throw New ArgumentException("The string representation of a byte cannot have more than two characters.")
         Else
            byteString = value
         End If   
      End Set
      Get
         Return byteString
      End Get
   End Property
   
   ' IConvertible implementations.
   Public Function GetTypeCode() As TypeCode _
                   Implements IConvertible.GetTypeCode
      Return TypeCode.Object
   End Function
   
   Public Function ToBoolean(provider As IFormatProvider) As Boolean _
                   Implements IConvertible.ToBoolean
      If signBit = SignBit.Zero Then
         Return False
      Else
         Return True
      End If
   End Function 
   
   Public Function ToByte(provider As IFormatProvider) As Byte _
                   Implements IConvertible.ToByte
      If signBit = signBit.Negative Then
         Throw New OverflowException(String.Format("{0} is out of range of the Byte type.", Convert.ToSByte(byteString, 16))) 
      Else
         Return Byte.Parse(byteString, NumberStyles.HexNumber)
      End If       
   End Function
   
   Public Function ToChar(provider As IFormatProvider) As Char _
                   Implements IConvertible.ToChar
      If signBit = signBit.Negative Then 
         Throw New OverflowException(String.Format("{0} is out of range of the Char type.", Convert.ToSByte(byteString, 16)))
      Else
         Dim byteValue As Byte = Byte.Parse(Me.byteString, NumberStyles.HexNumber)
         Return Convert.ToChar(byteValue)
      End If                
   End Function 
   
   Public Function ToDateTime(provider As IFormatProvider) As Date _
                   Implements IConvertible.ToDateTime
      Throw New InvalidCastException("ByteString to DateTime conversion is not supported.")
   End Function
   
   Public Function ToDecimal(provider As IFormatProvider) As Decimal _
                   Implements IConvertible.ToDecimal
      If signBit = signBit.Negative Then
         Dim byteValue As SByte = SByte.Parse(byteString, NumberStyles.HexNumber)
         Return Convert.ToDecimal(byteValue)
      Else
         Dim byteValue As Byte = Byte.Parse(byteString, NumberStyles.HexNumber)
         Return Convert.ToDecimal(byteValue)
      End If
   End Function
   
   Public Function ToDouble(provider As IFormatProvider) As Double _
                   Implements IConvertible.ToDouble
      If signBit = signBit.Negative Then
         Return Convert.ToDouble(SByte.Parse(byteString, NumberStyles.HexNumber))
      Else
         Return Convert.ToDouble(Byte.Parse(byteString, NumberStyles.HexNumber))
      End If   
   End Function   
   
   Public Function ToInt16(provider As IFormatProvider) As Int16 _
                   Implements IConvertible.ToInt16
      If signBit = signBit.Negative Then
         Return Convert.ToInt16(SByte.Parse(byteString, NumberStyles.HexNumber))
      Else
         Return Convert.ToInt16(Byte.Parse(byteString, NumberStyles.HexNumber))
      End If   
   End Function
   
   Public Function ToInt32(provider As IFormatProvider) As Int32 _
                   Implements IConvertible.ToInt32
      If signBit = signBit.Negative Then
         Return Convert.ToInt32(SByte.Parse(byteString, NumberStyles.HexNumber))
      Else
         Return Convert.ToInt32(Byte.Parse(byteString, NumberStyles.HexNumber))
      End If   
   End Function
   
   Public Function ToInt64(provider As IFormatProvider) As Int64 _
                   Implements IConvertible.ToInt64
      If signBit = signBit.Negative Then
         Return Convert.ToInt64(SByte.Parse(byteString, NumberStyles.HexNumber))
      Else
         Return Convert.ToInt64(Byte.Parse(byteString, NumberStyles.HexNumber))
      End If   
   End Function
   
   Public Function ToSByte(provider As IFormatProvider) As SByte _
                   Implements IConvertible.ToSByte
      If signBit = SignBit.Positive Then
         Try
            Return Convert.ToSByte(Byte.Parse(byteString, NumberStyles.HexNumber))
         Catch e As OverflowException
            Throw New OverflowException(String.Format("{0} is outside the range of the SByte type.", _
                                                   Byte.Parse(byteString, NumberStyles.HexNumber)), e)   
         End Try
      Else
         Return SByte.Parse(byteString, NumberStyles.HexNumber)
      End If
   End Function

   Public Function ToSingle(provider As IFormatProvider) As Single _
                   Implements IConvertible.ToSingle
      If signBit = signBit.Negative Then
         Return Convert.ToSingle(SByte.Parse(byteString, NumberStyles.HexNumber))
      Else
         Return Convert.ToSingle(Byte.Parse(byteString, NumberStyles.HexNumber))
      End If   
   End Function

   Public Overloads Function ToString(provider As IFormatProvider) As String _
                   Implements IConvertible.ToString
      Return Me.byteString
   End Function
   
   Public Function ToType(conversionType As Type, provider As IFormatProvider) As Object _
                   Implements IConvertible.ToType
      Select Case Type.GetTypeCode(conversionType)
         Case TypeCode.Boolean 
            Return Me.ToBoolean(Nothing)
         Case TypeCode.Byte
            Return Me.ToByte(Nothing)
         Case TypeCode.Char
            Return Me.ToChar(Nothing)
         Case TypeCode.DateTime
            Return Me.ToDateTime(Nothing)
         Case TypeCode.Decimal
            Return Me.ToDecimal(Nothing)
         Case TypeCode.Double
            Return Me.ToDouble(Nothing)
         Case TypeCode.Int16
            Return Me.ToInt16(Nothing)
         Case TypeCode.Int32
            Return Me.ToInt32(Nothing)
         Case TypeCode.Int64
            Return Me.ToInt64(Nothing)
         Case TypeCode.Object
            If GetType(ByteString).Equals(conversionType) Then
               Return Me
            Else
               Throw New InvalidCastException(String.Format("Conversion to a {0} is not supported.", conversionType.Name))
            End If 
         Case TypeCode.SByte
            Return Me.ToSByte(Nothing)
         Case TypeCode.Single
            Return Me.ToSingle(Nothing)
         Case TypeCode.String
            Return Me.ToString(Nothing)
         Case TypeCode.UInt16
            Return Me.ToUInt16(Nothing)
         Case TypeCode.UInt32
            Return Me.ToUInt32(Nothing)
         Case TypeCode.UInt64
            Return Me.ToUInt64(Nothing)   
         Case Else
            Throw New InvalidCastException(String.Format("Conversion to {0} is not supported.", conversionType.Name))   
            
      End Select
   End Function
   
   Public Function ToUInt16(provider As IFormatProvider) As UInt16 _
                   Implements IConvertible.ToUInt16
      If signBit = signBit.Negative Then
         Throw New OverflowException(String.Format("{0} is outside the range of the UInt16 type.", _
                                                   SByte.Parse(byteString, NumberStyles.HexNumber)))
      Else
         Return Convert.ToUInt16(Byte.Parse(byteString, NumberStyles.HexNumber))
      End If   
   End Function

   Public Function ToUInt32(provider As IFormatProvider) As UInt32 _
                   Implements IConvertible.ToUInt32
      If signBit = signBit.Negative Then
         Throw New OverflowException(String.Format("{0} is outside the range of the UInt32 type.", _
                                                   SByte.Parse(byteString, NumberStyles.HexNumber)))
      Else
         Return Convert.ToUInt32(Byte.Parse(byteString, NumberStyles.HexNumber))
      End If   
   End Function
   
   Public Function ToUInt64(provider As IFormatProvider) As UInt64 _
                   Implements IConvertible.ToUInt64
      If signBit = signBit.Negative Then
         Throw New OverflowException(String.Format("{0} is outside the range of the UInt64 type.", _
                                                   SByte.Parse(byteString, NumberStyles.HexNumber)))
      Else
         Return Convert.ToUInt64(Byte.Parse(byteString, NumberStyles.HexNumber))
      End If   
   End Function
   
End Structure

下列範例會具現化數個 ByteString 物件,並呼叫 ToByte(Object, IFormatProvider) 方法,以將它們轉換成位元組值。 它說明方法會 ToByte(Object, IFormatProvider) 包裝要轉換之 物件之 方法的呼叫 IConvertible.ToByte

public class Class1
{
   public static void Main()
   {
      byte positiveByte = 216;
      sbyte negativeByte = -101;

      ByteString positiveString = new ByteString();
      positiveString.Sign = (SignBit) Math.Sign(positiveByte);
      positiveString.Value = positiveByte.ToString("X2");

      ByteString negativeString = new ByteString();
      negativeString.Sign = (SignBit) Math.Sign(negativeByte);
      negativeString.Value = negativeByte.ToString("X2");

      try {
         Console.WriteLine("'{0}' converts to {1}.", positiveString.Value, Convert.ToByte(positiveString));
      }
      catch (OverflowException) {
         Console.WriteLine("0x{0} is outside the range of the Byte type.", positiveString.Value);
      }

      try {
         Console.WriteLine("'{0}' converts to {1}.", negativeString.Value, Convert.ToByte(negativeString));
      }
      catch (OverflowException) {
         Console.WriteLine("0x{0} is outside the range of the Byte type.", negativeString.Value);
      }
   }
}
// The example displays the following output:
//       'D8' converts to 216.
//       0x9B is outside the range of the Byte type.
let positiveByte = 216uy
let negativeByte = -101y

let mutable positiveString = ByteString()
positiveString.Sign <- Math.Sign positiveByte |> enum
positiveString.Value <- positiveByte.ToString "X2"

let mutable negativeString = ByteString()
negativeString.Sign <- Math.Sign negativeByte |> enum
negativeString.Value <- negativeByte.ToString "X2"

try
    printfn $"'{positiveString.Value}' converts to {Convert.ToByte positiveString}."
with :? OverflowException ->
    printfn $"0x{positiveString.Value} is outside the range of the Byte type."

try
    printfn $"'{negativeString.Value}' converts to {Convert.ToByte negativeString}."
with :? OverflowException ->
    printfn $"0x{negativeString.Value} is outside the range of the Byte type."

// The example displays the following output:
//       'D8' converts to 216.
//       0x9B is outside the range of the Byte type.
Module modMain
   Public Sub Main()
      Dim positiveByte As Byte = 216
      Dim negativeByte As SByte = -101
      
      
      Dim positiveString As New ByteString()
      positiveString.Sign = CType(Math.Sign(positiveByte), SignBit)
      positiveString.Value = positiveByte.ToString("X2")
      
      Dim negativeString As New ByteString()
      negativeString.Sign = CType(Math.Sign(negativeByte), SignBit)
      negativeString.Value = negativeByte.ToString("X2")
      
      Try
         Console.WriteLine("'{0}' converts to {1}.", positiveString.Value, Convert.ToByte(positiveString))
      Catch e As OverflowException
         Console.WriteLine("0x{0} is outside the range of the Byte type.", positiveString.Value)
      End Try

      Try
         Console.WriteLine("'{0}' converts to {1}.", negativeString.Value, Convert.ToByte(negativeString))
      Catch e As OverflowException
         Console.WriteLine("0x{0} is outside the range of the Byte type.", negativeString.Value)
      End Try   
   End Sub
End Module
' The example dosplays the following output:
'       'D8' converts to 216.
'       0x9B is outside the range of the Byte type.

備註

provider 可讓使用者指定 有關 內容 value的文化特性特定轉換資訊。 基底類型會忽略 provider;不過,如果 value 是實作 IConvertible 介面的使用者定義型別,可以使用 參數。

適用於

ToByte(String, IFormatProvider)

使用指定之特定文化特性格式資訊,將指定之數字的字串表示轉換為相等的 8 位元不帶正負號的整數。

public:
 static System::Byte ToByte(System::String ^ value, IFormatProvider ^ provider);
public static byte ToByte (string value, IFormatProvider provider);
public static byte ToByte (string? value, IFormatProvider? provider);
static member ToByte : string * IFormatProvider -> byte
Public Shared Function ToByte (value As String, provider As IFormatProvider) As Byte

參數

value
String

字串,包含要轉換的數字。

provider
IFormatProvider

物件,提供特定文化特性格式資訊。

傳回

8 位元不帶正負號的整數,等於 value;而若 valuenull,則為零。

例外狀況

value 不是由後面接著一連串數字 (0 到 9) 的任意符號所組成。

value 代表小於 Byte.MinValue 或大於 Byte.MaxValue 的數位。

範例

下列範例會建立自定義 NumberFormatInfo 物件,將正負號定義為 「pos」,並將負號定義為 「neg」,用於呼叫 ToByte(String, IFormatProvider) 方法。 然後,它會重複呼叫 ToByte(String, IFormatProvider) 方法,將字串陣列中的每個項目轉換成 Byte 值。

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      // Create a NumberFormatInfo object and set several of its
      // properties that apply to unsigned bytes.
      NumberFormatInfo provider = new NumberFormatInfo();

      // These properties affect the conversion.
      provider.PositiveSign = "pos ";
      provider.NegativeSign = "neg ";

      // This property does not affect the conversion.
      // The input string cannot have a decimal separator.
      provider.NumberDecimalSeparator = ".";

      // Define an array of numeric strings.
      string[] numericStrings = { "234", "+234", "pos 234", "234.", "255",
                                  "256", "-1" };

      foreach (string numericString in numericStrings)
      {
         Console.Write("'{0,-8}' ->   ", numericString);
         try {
            byte number = Convert.ToByte(numericString, provider);
            Console.WriteLine(number);
         }
         catch (FormatException) {
            Console.WriteLine("Incorrect Format");
         }
         catch (OverflowException) {
            Console.WriteLine("Overflows a Byte");
         }
      }
   }
}
// The example displays the following output:
//       '234     ' ->   234
//       '+234    ' ->   Incorrect Format
//       'pos 234 ' ->   234
//       '234.    ' ->   Incorrect Format
//       '255     ' ->   255
//       '256     ' ->   Overflows a Byte
//       '-1      ' ->   Incorrect Format
open System
open System.Globalization

// Create a NumberFormatInfo object and set several of its
// properties that apply to unsigned bytes.
let provider = NumberFormatInfo()

// These properties affect the conversion.
provider.PositiveSign <- "pos "
provider.NegativeSign <- "neg "

// This property does not affect the conversion.
// The input string cannot have a decimal separator.
provider.NumberDecimalSeparator <- "."

// Define an array of numeric strings.
let numericStrings = 
    [| "234"; "+234"; "pos 234"
       "234."; "255"; "256"; "-1" |]

for numericString in numericStrings do
    printf $"'{numericString,-8}' ->   "
    try
        let number = Convert.ToByte(numericString, provider)
        printfn $"{number}"
    with
    | :? FormatException ->
        printfn "Incorrect Format"
    | :? OverflowException ->
        printfn "Overflows a Byte"

// The example displays the following output:
//       '234     ' ->   234
//       '+234    ' ->   Incorrect Format
//       'pos 234 ' ->   234
//       '234.    ' ->   Incorrect Format
//       '255     ' ->   255
//       '256     ' ->   Overflows a Byte
//       '-1      ' ->   Incorrect Format
Imports System.Globalization

Module Example
   Public Sub Main()
      ' Create a NumberFormatInfo object and set several of its
      ' properties that apply to unsigned bytes.
      Dim provider As New NumberFormatInfo()
      With provider 
         ' These properties affect the conversion.
         .PositiveSign = "pos "
         .NegativeSign = "neg "

         ' This property does not affect the conversion.
         ' The input string cannot have a decimal separator.
         .NumberDecimalSeparator = "."
      End With
      
      ' Define an array of numeric strings.
      Dim numericStrings() As String = { "234", "+234", "pos 234", "234.", _
                                         "255", "256", "-1" }

      For Each numericString As String In numericStrings
         Console.Write("'{0,-8}' ->   ", numericString)
         Try
            Dim number As Byte = Convert.ToByte(numericString, provider)
            Console.WriteLine(number)
         Catch ex As FormatException
            Console.WriteLine("Incorrect Format")                          
         Catch ex As OverflowException
            Console.WriteLine("Overflows a Byte")
         End Try   
      Next
   End Sub   
End Module 
' The example displays the following output:
'       '234     ' ->   234
'       '+234    ' ->   Incorrect Format
'       'pos 234 ' ->   234
'       '234.    ' ->   Incorrect Format
'       '255     ' ->   255
'       '256     ' ->   Overflows a Byte
'       '-1      ' ->   Incorrect Format

備註

providerIFormatProvider是取得 NumberFormatInfo 對象的實例。 物件 NumberFormatInfo 提供有關 格式 value的文化特性特定資訊。 如果 為 providernull,則會 NumberFormatInfo 使用目前文化特性的物件。

如果您不想在轉換失敗時處理例外狀況,您可以改為呼叫 Byte.TryParse 方法。 它會傳回值 Boolean ,指出轉換成功或失敗。

另請參閱

適用於

ToByte(Single)

將指定之單精確度浮點數的值,轉換為相等的 8 位元不帶正負號的整數。

public:
 static System::Byte ToByte(float value);
public static byte ToByte (float value);
static member ToByte : single -> byte
Public Shared Function ToByte (value As Single) As Byte

參數

value
Single

單精確度浮點數。

傳回

value,四捨五入為最接近的 8 位元不帶正負號整數。 如果 value 介於兩個整數正中間時,則傳回偶數;也就是 4.5 會轉換為 4,5.5 會轉換為 6。

例外狀況

value 大於 Byte.MaxValue 或小於 Byte.MinValue

範例

下列範例會將 Single 值轉換為 Byte

public:
   void ConvertByteSingle( Byte byteVal )
   {
      float floatVal;
      
      // Byte to float conversion will not overflow.
      floatVal = System::Convert::ToSingle( byteVal );
      System::Console::WriteLine( "The Byte as a float is {0}.",
         floatVal );
      
      // Float to Byte conversion can overflow.
      try
      {
         byteVal = System::Convert::ToByte( floatVal );
         System::Console::WriteLine( "The float as a Byte is {0}.",
         byteVal );
      }
      catch ( System::OverflowException^ ) 
      {
         System::Console::WriteLine(
            "The float value is too large for a Byte." );
      }
   }
public void ConvertByteSingle(byte byteVal) {
    float floatVal;

    // Byte to float conversion will not overflow.
    floatVal = System.Convert.ToSingle(byteVal);
    System.Console.WriteLine("The byte as a float is {0}.",
        floatVal);

    // Float to byte conversion can overflow.
    try {
        byteVal = System.Convert.ToByte(floatVal);
        System.Console.WriteLine("The float as a byte is {0}.",
            byteVal);
    }
    catch (System.OverflowException) {
        System.Console.WriteLine(
            "The float value is too large for a byte.");
    }
}
let convertByteSingle (byteVal: byte) =
    // Byte to float conversion will not overflow.
    let floatVal = Convert.ToSingle byteVal
    printfn $"The byte as a float is {floatVal}."

    // Float to byte conversion can overflow.
    try
        let byteVal = Convert.ToByte floatVal
        printfn $"The float as a byte is {byteVal}."
    with :? OverflowException ->
        printfn "The float value is too large for a byte."
Public Sub ConvertByteSingle(ByVal byteVal As Byte)
    Dim singleVal As Single

    ' Byte to float conversion will not overflow.
    singleVal = System.Convert.ToSingle(byteVal)
    System.Console.WriteLine("The byte as a single is {0}.", _
                              singleVal)

    ' Single to byte conversion can overflow.
    Try
        byteVal = System.Convert.ToByte(singleVal)
        System.Console.WriteLine("The single as a byte is {0}.", _
                                  byteVal)
    Catch exception As System.OverflowException
        System.Console.WriteLine( _
            "Overflow in single-to-byte conversion.")
    End Try
End Sub

另請參閱

適用於

ToByte(UInt64)

重要

此 API 不符合 CLS 規範。

將指定的 64 位元不帶正負號整數的值,轉換為相等的 8 位元不帶正負號整數。

public:
 static System::Byte ToByte(System::UInt64 value);
[System.CLSCompliant(false)]
public static byte ToByte (ulong value);
[<System.CLSCompliant(false)>]
static member ToByte : uint64 -> byte
Public Shared Function ToByte (value As ULong) As Byte

參數

value
UInt64

要轉換之 64 位元不帶正負號的整數。

傳回

等於 value 的 8 位元不帶正負號整數。

屬性

例外狀況

範例

下列範例會將不帶正負號長整數的陣列轉換為 Byte 值。

ulong[] numbers= { UInt64.MinValue, 121, 340, UInt64.MaxValue };
byte result;
foreach (ulong number in numbers)
{
   try {
      result = Convert.ToByte(number);
      Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.",
                        number.GetType().Name, number,
                        result.GetType().Name, result);
   }
   catch (OverflowException)
   {
      Console.WriteLine("The {0} value {1} is outside the range of the Byte type.",
                        number.GetType().Name, number);
   }
}
// The example displays the following output:
//       Converted the UInt64 value 0 to the Byte value 0.
//       Converted the UInt64 value 121 to the Byte value 121.
//       The UInt64 value 340 is outside the range of the Byte type.
//       The UInt64 value 18446744073709551615 is outside the range of the Byte type.
let numbers= [| UInt64.MinValue; 121uL; 340uL; UInt64.MaxValue |]
for number in numbers do
    try
        let result = Convert.ToByte number
        printfn $"Converted the {number.GetType().Name} value {number} to the {result.GetType().Name} value {result}."
    with :? OverflowException ->
        printfn $"The {number.GetType().Name} value {number} is outside the range of the Byte type."
// The example displays the following output:
//       Converted the UInt64 value 0 to the Byte value 0.
//       Converted the UInt64 value 121 to the Byte value 121.
//       The UInt64 value 340 is outside the range of the Byte type.
//       The UInt64 value 18446744073709551615 is outside the range of the Byte type.
Dim numbers() As ULong = { UInt64.MinValue, 121, 340, UInt64.MaxValue }
Dim result As Byte
For Each number As ULong In numbers
   Try
      result = Convert.ToByte(number)
      Console.WriteLIne("Converted the {0} value {1} to the {2} value {3}.", _
                        number.GetType().Name, number, _
                        result.GetType().Name, result)
   Catch e As OverflowException
      Console.WriteLine("The {0} value {1} is outside the range of the Byte type.", _
                        number.GetType().Name, number)
   End Try
Next
' The example displays the following output:
'       Converted the UInt64 value 0 to the Byte value 0.
'       Converted the UInt64 value 121 to the Byte value 121.
'       The UInt64 value 340 is outside the range of the Byte type.
'       The UInt64 value 18446744073709551615 is outside the range of the Byte type.

適用於

ToByte(SByte)

重要

此 API 不符合 CLS 規範。

將指定的 8 位元帶正負號的整數值轉換為相等的 8 位元不帶正負號的整數。

public:
 static System::Byte ToByte(System::SByte value);
[System.CLSCompliant(false)]
public static byte ToByte (sbyte value);
[<System.CLSCompliant(false)>]
static member ToByte : sbyte -> byte
Public Shared Function ToByte (value As SByte) As Byte

參數

value
SByte

要轉換的 8 位元帶正負號的整數。

傳回

等於 value 的 8 位元不帶正負號整數。

屬性

例外狀況

範例

下列範例會將值的陣列 SByte 轉換成 Byte 值。

sbyte[] numbers = { SByte.MinValue, -1, 0, 10, SByte.MaxValue };
byte result;
foreach (sbyte number in numbers)
{
   try {
      result = Convert.ToByte(number);
      Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.",
                        number.GetType().Name, number,
                        result.GetType().Name, result);
   }
   catch (OverflowException)
   {
      Console.WriteLine("The {0} value {1} is outside the range of the Byte type.",
                        number.GetType().Name, number);
   }
}
// The example displays the following output:
//       The SByte value -128 is outside the range of the Byte type.
//       The SByte value -1 is outside the range of the Byte type.
//       Converted the SByte value 0 to the Byte value 0.
//       Converted the SByte value 10 to the Byte value 10.
//       Converted the SByte value 127 to the Byte value 127.
let numbers = [| SByte.MinValue; -1y; 0y; 10y; SByte.MaxValue |]
for number in numbers do
    try
        let result = Convert.ToByte number
        printfn $"Converted the {number.GetType().Name} value {number} to the {result.GetType().Name} value {result}."
    with :? OverflowException ->
        printfn $"The {number.GetType().Name} value {number} is outside the range of the Byte type."
// The example displays the following output:
//       The SByte value -128 is outside the range of the Byte type.
//       The SByte value -1 is outside the range of the Byte type.
//       Converted the SByte value 0 to the Byte value 0.
//       Converted the SByte value 10 to the Byte value 10.
//       Converted the SByte value 127 to the Byte value 127.
Dim numbers() As SByte = { SByte.MinValue, -1, 0, 10, SByte.MaxValue }
Dim result As Byte
For Each number As SByte In numbers
   Try
      result = Convert.ToByte(number)
      Console.WriteLIne("Converted the {0} value {1} to the {2} value {3}.", _
                        number.GetType().Name, number, _
                        result.GetType().Name, result)
   Catch e As OverflowException
      Console.WriteLine("The {0} value {1} is outside the range of the Byte type.", _
                        number.GetType().Name, number)
   End Try
Next
' The example displays the following output:
'       The SByte value -128 is outside the range of the Byte type.
'       The SByte value -1 is outside the range of the Byte type.
'       Converted the SByte value 0 to the Byte value 0.
'       Converted the SByte value 10 to the Byte value 10.
'       Converted the SByte value 127 to the Byte value 127.

適用於

ToByte(DateTime)

呼叫這個方法一律會擲回 InvalidCastException

public:
 static System::Byte ToByte(DateTime value);
public static byte ToByte (DateTime value);
static member ToByte : DateTime -> byte
Public Shared Function ToByte (value As DateTime) As Byte

參數

value
DateTime

要轉換的日期和時間值。

傳回

不支援此轉換。 沒有傳回值。

例外狀況

不支援此轉換。

適用於

ToByte(Int64)

將指定的 64 位元帶正負號的整數值轉換為相等的 8 位元不帶正負號的整數。

public:
 static System::Byte ToByte(long value);
public static byte ToByte (long value);
static member ToByte : int64 -> byte
Public Shared Function ToByte (value As Long) As Byte

參數

value
Int64

要轉換的 64 位元帶正負號的整數。

傳回

等於 value 的 8 位元不帶正負號整數。

例外狀況

value 小於 Byte.MinValue 或大於 Byte.MaxValue

範例

下列範例會將值的陣列 Int64 轉換成 Byte 值。

long[] numbers = { Int64.MinValue, -1, 0, 121, 340, Int64.MaxValue };
byte result;
foreach (long number in numbers)
{
   try {
      result = Convert.ToByte(number);
      Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.",
                        number.GetType().Name, number,
                        result.GetType().Name, result);
   }
   catch (OverflowException) {
      Console.WriteLine("The {0} value {1} is outside the range of the Byte type.",
                        number.GetType().Name, number);
   }
}
// The example displays the following output:
//       The Int64 value -9223372036854775808 is outside the range of the Byte type.
//       The Int64 value -1 is outside the range of the Byte type.
//       Converted the Int64 value 0 to the Byte value 0.
//       Converted the Int64 value 121 to the Byte value 121.
//       The Int64 value 340 is outside the range of the Byte type.
//       The Int64 value 9223372036854775807 is outside the range of the Byte type.
let numbers = [| Int64.MinValue; -1L; 0L; 121L; 34L; Int64.MaxValue |]
for number in numbers do
    try
        let result = Convert.ToByte number
        printfn $"Converted the {number.GetType().Name} value {number} to the {result.GetType().Name} value {result}."
    with :? OverflowException ->
        printfn $"The {number.GetType().Name} value {number} is outside the range of the Byte type."
// The example displays the following output:
//       The Int64 value -9223372036854775808 is outside the range of the Byte type.
//       The Int64 value -1 is outside the range of the Byte type.
//       Converted the Int64 value 0 to the Byte value 0.
//       Converted the Int64 value 121 to the Byte value 121.
//       The Int64 value 340 is outside the range of the Byte type.
//       The Int64 value 9223372036854775807 is outside the range of the Byte type.
Dim numbers() As Long = { Int64.MinValue, -1, 0, 121, 340, Int64.MaxValue }
Dim result As Byte
For Each number As Long In numbers
   Try
      result = Convert.ToByte(number)
      Console.WriteLIne("Converted the {0} value {1} to the {2} value {3}.", _
                        number.GetType().Name, number, _
                        result.GetType().Name, result)
   Catch e As OverflowException
      Console.WriteLine("The {0} value {1} is outside the range of the Byte type.", _
                        number.GetType().Name, number)
   End Try
Next
' The example displays the following output:
'       The Int64 value -9223372036854775808 is outside the range of the Byte type.
'       The Int64 value -1 is outside the range of the Byte type.
'       Converted the Int64 value 0 to the Byte value 0.
'       Converted the Int64 value 121 to the Byte value 121.
'       The Int64 value 340 is outside the range of the Byte type.
'       The Int64 value 9223372036854775807 is outside the range of the Byte type.

適用於

ToByte(Byte)

傳回指定的 8 位元不帶正負號整數;不會執行實際的轉換。

public:
 static System::Byte ToByte(System::Byte value);
public static byte ToByte (byte value);
static member ToByte : byte -> byte
Public Shared Function ToByte (value As Byte) As Byte

參數

value
Byte

要傳回之 8 位元不帶正負號的整數。

傳回

value 會原封不動地傳回。

適用於

ToByte(Char)

將指定的 Unicode 字元值轉換為相等的 8 位元不帶正負號的整數。

public:
 static System::Byte ToByte(char value);
public static byte ToByte (char value);
static member ToByte : char -> byte
Public Shared Function ToByte (value As Char) As Byte

參數

value
Char

要轉換的 Unicode 字元。

傳回

等於 value 的 8 位元不帶正負號整數。

例外狀況

value 代表大於 Byte.MaxValue 的數位。

範例

下列範例會將值的陣列 Char 轉換成 Byte 值。

char[] chars = { 'a', 'z', '\x0007', '\x03FF' };
foreach (char ch in chars)
{
   try {
      byte result = Convert.ToByte(ch);
      Console.WriteLine("{0} is converted to {1}.", ch, result);
   }
   catch (OverflowException) {
      Console.WriteLine("Unable to convert u+{0} to a byte.",
                        Convert.ToInt16(ch).ToString("X4"));
   }
}
// The example displays the following output:
//       a is converted to 97.
//       z is converted to 122.
//        is converted to 7.
//       Unable to convert u+03FF to a byte.
let chars = [| 'a'; 'z'; '\u0007'; '\u03FF' |]
for ch in chars do
    try
        let result = Convert.ToByte ch
        printfn $"{ch} is converted to {result}."
    with :? OverflowException ->
        printfn $"Unable to convert u+{Convert.ToInt16 ch:X4} to a byte."
// The example displays the following output:
//       a is converted to 97.
//       z is converted to 122.
//        is converted to 7.
//       Unable to convert u+03FF to a byte.
Dim chars() As Char = { "a"c, "z"c, ChrW(7), ChrW(1023) }
For Each ch As Char in chars
   Try
      Dim result As Byte = Convert.ToByte(ch)
      Console.WriteLine("{0} is converted to {1}.", ch, result)
   Catch e As OverflowException
      Console.WriteLIne("Unable to convert u+{0} to a byte.", _
                        AscW(ch).ToString("X4"))
   End Try
Next   
' The example displays the following output:
'       a is converted to 97.
'       z is converted to 122.
'        is converted to 7.
'       Unable to convert u+03FF to a byte.

備註

這個方法會傳回不帶正負號的位元元組值,代表傳遞給它的 物件數值碼 Char 。 在 .NET 中 Char ,物件是16位值。 這表示方法適用於傳回 ASCII 字元範圍或 Unicode C0 Controls 和 Basic Latin 中的字元數位碼,以及 C1 Controls 和 Latin-1 補充範圍,從 U+0000 到 U+00FF。

適用於

ToByte(Decimal)

將指定之十進位數字的值,轉換為相等的 8 位元不帶正負號的整數。

public:
 static System::Byte ToByte(System::Decimal value);
public static byte ToByte (decimal value);
static member ToByte : decimal -> byte
Public Shared Function ToByte (value As Decimal) As Byte

參數

value
Decimal

要轉換的數字。

傳回

value,四捨五入為最接近的 8 位元不帶正負號整數。 如果 value 介於兩個整數正中間時,則傳回偶數;也就是 4.5 會轉換為 4,5.5 會轉換為 6。

例外狀況

value 大於 Byte.MaxValue 或小於 Byte.MinValue

備註

下列範例會將 Byte 值轉換為 , Decimal 並將 Decimal 值轉換為 Byte

public:
   void ConvertByteDecimal( Byte byteVal )
   {
      Decimal decimalVal;
      
      // Byte to decimal conversion will not overflow.
      decimalVal = System::Convert::ToDecimal( byteVal );
      System::Console::WriteLine( "The Byte as a decimal is {0}.",
         decimalVal );
      
      // Decimal to Byte conversion can overflow.
      try
      {
         byteVal = System::Convert::ToByte( decimalVal );
         System::Console::WriteLine( "The Decimal as a Byte is {0}.",
         byteVal );
      }
      catch ( System::OverflowException^ ) 
      {
         System::Console::WriteLine(
            "The decimal value is too large for a Byte." );
      }
   }
public void ConvertByteDecimal(byte byteVal) {
    decimal decimalVal;

    // Byte to decimal conversion will not overflow.
    decimalVal = System.Convert.ToDecimal(byteVal);
    System.Console.WriteLine("The byte as a decimal is {0}.",
        decimalVal);

    // Decimal to byte conversion can overflow.
    try {
        byteVal = System.Convert.ToByte(decimalVal);
        System.Console.WriteLine("The Decimal as a byte is {0}.",
            byteVal);
    }
    catch (System.OverflowException) {
        System.Console.WriteLine(
            "The decimal value is too large for a byte.");
    }
}
let convertByteDecimal (byteVal: byte) =
    // Byte to decimal conversion will not overflow.
    let decimalVal = Convert.ToDecimal byteVal
    printfn $"The byte as a decimal is {decimalVal}."

    // Decimal to byte conversion can overflow.
    try
        let byteVal = Convert.ToByte decimalVal
        printfn $"The Decimal as a byte is {byteVal}."
    with :? OverflowException ->
        printfn "The decimal value is too large for a byte."
Public Sub ConvertByteDecimal(ByVal byteVal As Byte)
    Dim decimalVal As Decimal

    ' Byte to decimal conversion will not overflow.
    decimalVal = System.Convert.ToDecimal(byteVal)
    System.Console.WriteLine("The byte as a decimal is {0}.", _
                              decimalVal)

    ' Decimal to byte conversion can overflow.
    Try
        byteVal = System.Convert.ToByte(decimalVal)
        System.Console.WriteLine("The Decimal as a byte is {0}.", _
                                  byteVal)
    Catch exception As System.OverflowException
        System.Console.WriteLine( _
            "Overflow in decimal-to-byte conversion.")
    End Try
End Sub

適用於

ToByte(Boolean)

將指定的布林值轉換為相等的 8 位元不帶正負號的整數。

public:
 static System::Byte ToByte(bool value);
public static byte ToByte (bool value);
static member ToByte : bool -> byte
Public Shared Function ToByte (value As Boolean) As Byte

參數

value
Boolean

要轉換的布林值。

傳回

如果 valuetrue,則為數字 1,否則為 0。

範例

下列範例說明 如何將 Boolean 轉換成 Byte 值。

using namespace System;

void main()
{
   bool falseFlag = false;
   bool trueFlag = true;

   Console::WriteLine("{0} converts to {1}.", falseFlag,
                      Convert::ToByte(falseFlag));
   Console::WriteLine("{0} converts to {1}.", trueFlag, 
                      Convert::ToByte(trueFlag));
}
// The example displays the following output:
//       False converts to 0.
//       True converts to 1.
bool falseFlag = false;
bool trueFlag = true;

Console.WriteLine("{0} converts to {1}.", falseFlag,
                  Convert.ToByte(falseFlag));
Console.WriteLine("{0} converts to {1}.", trueFlag,
                  Convert.ToByte(trueFlag));
// The example displays the following output:
//       False converts to 0.
//       True converts to 1.
let falseFlag = false
let trueFlag = true

printfn $"{falseFlag} converts to {Convert.ToByte falseFlag}."
printfn $"{trueFlag} converts to {Convert.ToByte trueFlag}."
// The example displays the following output:
//       False converts to 0.
//       True converts to 1.
Dim falseFlag As Boolean = False
Dim trueFlag As Boolean = True

Console.WriteLine("{0} converts to {1}.", falseFlag, _
                  Convert.ToByte(falseFlag))
Console.WriteLine("{0} converts to {1}.", trueFlag, _
                  Convert.ToByte(trueFlag))
' The example displays the following output:
'       False converts to 0.
'       True converts to 1.

適用於

ToByte(Int16)

將指定的 16 位元帶正負號的整數值轉換為相等的 8 位元不帶正負號的整數。

public:
 static System::Byte ToByte(short value);
public static byte ToByte (short value);
static member ToByte : int16 -> byte
Public Shared Function ToByte (value As Short) As Byte

參數

value
Int16

要轉換的 16 位元帶正負號的整數。

傳回

等於 value 的 8 位元不帶正負號整數。

例外狀況

value 小於 Byte.MinValue 或大於 Byte.MaxValue

範例

下列範例會將值的陣列 Int16 轉換成 Byte 值。

short[] numbers = { Int16.MinValue, -1, 0, 121, 340, Int16.MaxValue };
byte result;
foreach (short number in numbers)
{
   try {
      result = Convert.ToByte(number);
      Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.",
                        number.GetType().Name, number,
                        result.GetType().Name, result);
   }
   catch (OverflowException) {
      Console.WriteLine("The {0} value {1} is outside the range of the Byte type.",
                        number.GetType().Name, number);
   }
}
// The example displays the following output:
//       The Int16 value -32768 is outside the range of the Byte type.
//       The Int16 value -1 is outside the range of the Byte type.
//       Converted the Int16 value 0 to the Byte value 0.
//       Converted the Int16 value 121 to the Byte value 121.
//       The Int16 value 340 is outside the range of the Byte type.
//       The Int16 value 32767 is outside the range of the Byte type.
let numbers = [| Int16.MinValue; -1s; 0s; 121s; 340s; Int16.MaxValue |]
for number in numbers do
    try
        let result = Convert.ToByte number
        printfn $"Converted the {number.GetType().Name} value {number} to the {result.GetType().Name} value {result}."
    with :? OverflowException ->
        printfn $"The {number.GetType().Name} value {number} is outside the range of the Byte type."
// The example displays the following output:
//       The Int16 value -32768 is outside the range of the Byte type.
//       The Int16 value -1 is outside the range of the Byte type.
//       Converted the Int16 value 0 to the Byte value 0.
//       Converted the Int16 value 121 to the Byte value 121.
//       The Int16 value 340 is outside the range of the Byte type.
//       The Int16 value 32767 is outside the range of the Byte type.
Dim numbers() As Short = { Int16.MinValue, -1, 0, 121, 340, Int16.MaxValue }
Dim result As Byte
For Each number As Short In numbers
   Try
      result = Convert.ToByte(number)
      Console.WriteLIne("Converted the {0} value {1} to the {2} value {3}.", _
                        number.GetType().Name, number, _
                        result.GetType().Name, result)
   Catch e As OverflowException
      Console.WriteLine("The {0} value {1} is outside the range of the Byte type.", _
                        number.GetType().Name, number)
   End Try
Next
' The example displays the following output:
'       The Int16 value -32768 is outside the range of the Byte type.
'       The Int16 value -1 is outside the range of the Byte type.
'       Converted the Int16 value 0 to the Byte value 0.
'       Converted the Int16 value 121 to the Byte value 121.
'       The Int16 value 340 is outside the range of the Byte type.
'       The Int16 value 32767 is outside the range of the Byte type.

適用於

ToByte(Int32)

將指定的 32 位元帶正負號的整數值轉換為相等的 8 位元不帶正負號的整數。

public:
 static System::Byte ToByte(int value);
public static byte ToByte (int value);
static member ToByte : int -> byte
Public Shared Function ToByte (value As Integer) As Byte

參數

value
Int32

要轉換的 32 位元帶正負號的整數。

傳回

等於 value 的 8 位元不帶正負號整數。

例外狀況

value 小於 Byte.MinValue 或大於 Byte.MaxValue

範例

下列範例會將值的陣列 Int32 轉換成 Byte 值。

int[] numbers = { Int32.MinValue, -1, 0, 121, 340, Int32.MaxValue };
byte result;
foreach (int number in numbers)
{
   try {
      result = Convert.ToByte(number);
      Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.",
                        number.GetType().Name, number,
                        result.GetType().Name, result);
   }
   catch (OverflowException) {
      Console.WriteLine("The {0} value {1} is outside the range of the Byte type.",
                        number.GetType().Name, number);
   }
}
// The example displays the following output:
//       The Int32 value -2147483648 is outside the range of the Byte type.
//       The Int32 value -1 is outside the range of the Byte type.
//       Converted the Int32 value 0 to the Byte value 0.
//       Converted the Int32 value 121 to the Byte value 121.
//       The Int32 value 340 is outside the range of the Byte type.
//       The Int32 value 2147483647 is outside the range of the Byte type.
let numbers = [| Int32.MinValue; -1; 0; 121; 340; Int32.MaxValue |]
for number in numbers do
    try
        let result = Convert.ToByte number
        printfn $"Converted the {number.GetType().Name} value {number} to the {result.GetType().Name} value {result}."
    with :? OverflowException ->
        printfn $"The {number.GetType().Name} value {number} is outside the range of the Byte type."
// The example displays the following output:
//       The Int32 value -2147483648 is outside the range of the Byte type.
//       The Int32 value -1 is outside the range of the Byte type.
//       Converted the Int32 value 0 to the Byte value 0.
//       Converted the Int32 value 121 to the Byte value 121.
//       The Int32 value 340 is outside the range of the Byte type.
//       The Int32 value 2147483647 is outside the range of the Byte type.
Dim numbers() As Integer = { Int32.MinValue, -1, 0, 121, 340, Int32.MaxValue }
Dim result As Byte
For Each number As Integer In numbers
   Try
      result = Convert.ToByte(number)
      Console.WriteLIne("Converted the {0} value {1} to the {2} value {3}.", _
                        number.GetType().Name, number, _
                        result.GetType().Name, result)
   Catch e As OverflowException
      Console.WriteLine("The {0} value {1} is outside the range of the Byte type.", _
                        number.GetType().Name, number)
   End Try
Next
' The example displays the following output:
'       The Int32 value -2147483648 is outside the range of the Byte type.
'       The Int32 value -1 is outside the range of the Byte type.
'       Converted the Int32 value 0 to the Byte value 0.
'       Converted the Int32 value 121 to the Byte value 121.
'       The Int32 value 340 is outside the range of the Byte type.
'       The Int32 value 2147483647 is outside the range of the Byte type.

適用於

ToByte(Double)

將指定之雙精確度浮點數的值,轉換為相等的 8 位元不帶正負號的整數。

public:
 static System::Byte ToByte(double value);
public static byte ToByte (double value);
static member ToByte : double -> byte
Public Shared Function ToByte (value As Double) As Byte

參數

value
Double

要轉換的雙精確度浮點數。

傳回

value,四捨五入為最接近的 8 位元不帶正負號整數。 如果 value 介於兩個整數正中間時,則傳回偶數;也就是 4.5 會轉換為 4,5.5 會轉換為 6。

例外狀況

value 大於 Byte.MaxValue 或小於 Byte.MinValue

範例

下列範例會將 Byte 值轉換為 , Double 並將 Double 值轉換為 Byte

public:
   void ConvertDoubleByte( double doubleVal )
   {
      Byte byteVal = 0;
      
      // Double to Byte conversion can overflow.
      try
      {
         byteVal = System::Convert::ToByte( doubleVal );
         System::Console::WriteLine( " {0} as a Byte is: {1}.",
         doubleVal, byteVal );
      }
      catch ( System::OverflowException^ ) 
      {
         System::Console::WriteLine( "Overflow in double-to-Byte conversion." );
      }
      
      // Byte to double conversion cannot overflow.
      doubleVal = System::Convert::ToDouble( byteVal );
      System::Console::WriteLine( " {0} as a double is: {1}.",
         byteVal, doubleVal );
   }
public void ConvertDoubleByte(double doubleVal) {
    byte	byteVal = 0;

    // Double to byte conversion can overflow.
    try {
        byteVal = System.Convert.ToByte(doubleVal);
        System.Console.WriteLine("{0} as a byte is: {1}.",
            doubleVal, byteVal);
    }
    catch (System.OverflowException) {
        System.Console.WriteLine(
            "Overflow in double-to-byte conversion.");
    }

    // Byte to double conversion cannot overflow.
    doubleVal = System.Convert.ToDouble(byteVal);
    System.Console.WriteLine("{0} as a double is: {1}.",
        byteVal, doubleVal);
}
let convertDoubleByte (doubleVal: float) =
    // Double to byte conversion can overflow.
    try
        let byteVal = Convert.ToByte doubleVal
        printfn $"{doubleVal} as a byte is: {byteVal}."
        
        // Byte to double conversion cannot overflow.
        let doubleVal = Convert.ToDouble byteVal
        printfn $"{byteVal} as a double is: {doubleVal}."
    with :? OverflowException ->
        printfn "Overflow in double-to-byte conversion."
Public Sub ConvertDoubleByte(ByVal doubleVal As Double)
    Dim byteVal As Byte = 0

    ' Double to Byte conversion can overflow.
    Try
        byteVal = System.Convert.ToByte(doubleVal)
        System.Console.WriteLine("{0} as a Byte is: {1}.", _
            doubleVal, byteVal)
    Catch exception As System.OverflowException
        System.Console.WriteLine( _
            "Overflow in Double-to-Byte conversion.")
    End Try

    ' Byte to Double conversion cannot overflow.
    doubleVal = System.Convert.ToDouble(byteVal)
    System.Console.WriteLine("{0} as a Double is: {1}.", _
                              byteVal, doubleVal)
End Sub

適用於

ToByte(Object)

將指定之物件的值轉換為 8 位元不帶正負號的整數。

public:
 static System::Byte ToByte(System::Object ^ value);
public static byte ToByte (object value);
public static byte ToByte (object? value);
static member ToByte : obj -> byte
Public Shared Function ToByte (value As Object) As Byte

參數

value
Object

實作 IConvertible 介面的物件,或是 null

傳回

8 位元不帶正負號的整數,等於 value;而若 valuenull,則為零。

例外狀況

value 的屬性格式不適用於 Byte 值。

value 未實作 IConvertible

-或-

不支援從 value 轉換至 Byte 類型。

value 代表小於 Byte.MinValue 或大於 Byte.MaxValue 的數位。

範例

下列範例會 ToByte(Object) 使用 方法,將 對象的數位轉換成 Byte 值。

object[] values = { true, -12, 163, 935, 'x', "104", "103.0", "-1",
                    "1.00e2", "One", 1.00e2};
byte result;
foreach (object value in values)
{
   try {
      result = Convert.ToByte(value);
      Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.",
                        value.GetType().Name, value,
                        result.GetType().Name, result);
   }
   catch (OverflowException)
   {
      Console.WriteLine("The {0} value {1} is outside the range of the Byte type.",
                        value.GetType().Name, value);
   }
   catch (FormatException)
   {
      Console.WriteLine("The {0} value {1} is not in a recognizable format.",
                        value.GetType().Name, value);
   }
   catch (InvalidCastException)
   {
      Console.WriteLine("No conversion to a Byte exists for the {0} value {1}.",
                        value.GetType().Name, value);
   }
}
// The example displays the following output:
//       Converted the Boolean value True to the Byte value 1.
//       The Int32 value -12 is outside the range of the Byte type.
//       Converted the Int32 value 163 to the Byte value 163.
//       The Int32 value 935 is outside the range of the Byte type.
//       Converted the Char value x to the Byte value 120.
//       Converted the String value 104 to the Byte value 104.
//       The String value 103.0 is not in a recognizable format.
//       The String value -1 is outside the range of the Byte type.
//       The String value 1.00e2 is not in a recognizable format.
//       The String value One is not in a recognizable format.
//       Converted the Double value 100 to the Byte value 100.
let values: obj[] = 
    [| true; -12; 163; 935; 'x'; "104"; "103.0" 
       "-1"; "1.00e2"; "One"; 1.00e2 |]
for value in values do
    try
        let result = Convert.ToByte value
        printfn $"Converted the {value.GetType().Name} value {value} to the {result.GetType().Name} value {result}."
    with
    | :? OverflowException ->
        printfn $"The {value.GetType().Name} value {value} is outside the range of the Byte type."
    | :? FormatException ->
        printfn $"The {value.GetType().Name} value {value} is not in a recognizable format."
    | :? InvalidCastException ->
        printfn $"No conversion to a Byte exists for the {value.GetType().Name} value {value}."
// The example displays the following output:
//       Converted the Boolean value True to the Byte value 1.
//       The Int32 value -12 is outside the range of the Byte type.
//       Converted the Int32 value 163 to the Byte value 163.
//       The Int32 value 935 is outside the range of the Byte type.
//       Converted the Char value x to the Byte value 120.
//       Converted the String value 104 to the Byte value 104.
//       The String value 103.0 is not in a recognizable format.
//       The String value -1 is outside the range of the Byte type.
//       The String value 1.00e2 is not in a recognizable format.
//       The String value One is not in a recognizable format.
//       Converted the Double value 100 to the Byte value 100.
Dim values() As Object = { True, -12, 163, 935, "x"c, "104", "103.0", "-1", _
                           "1.00e2", "One", 1.00e2}
Dim result As Byte
For Each value As Object In values
   Try
      result = Convert.ToByte(value)
      Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.", _
                        value.GetType().Name, value, _
                        result.GetType().Name, result)
   Catch e As OverflowException
      Console.WriteLine("The {0} value {1} is outside the range of the Byte type.", _
                        value.GetType().Name, value)
   Catch e As FormatException
      Console.WriteLine("The {0} value {1} is not in a recognizable format.", _
                        value.GetType().Name, value)
   Catch e As InvalidCastException
      Console.WriteLine("No conversion to a Byte exists for the {0} value {1}.", _
                        value.GetType().Name, value)
                        
   End Try
Next                           
' The example displays the following output:
'       Converted the Boolean value True to the Byte value 1.
'       The Int32 value -12 is outside the range of the Byte type.
'       Converted the Int32 value 163 to the Byte value 163.
'       The Int32 value 935 is outside the range of the Byte type.
'       Converted the Char value x to the Byte value 120.
'       Converted the String value 104 to the Byte value 104.
'       The String value 103.0 is not in a recognizable format.
'       The String value -1 is outside the range of the Byte type.
'       The String value 1.00e2 is not in a recognizable format.
'       The String value One is not in a recognizable format.
'       Converted the Double value 100 to the Byte value 100.

備註

如果 value 不是 null,這個方法會包裝對 基礎型別value實作的呼叫IConvertible.ToByte

適用於