📜  C#中的Decimal.ToByte()方法

📅  最后修改于: 2021-05-29 14:17:03             🧑  作者: Mango

此方法用于将指定的Decimal的值转换为等效的8位无符号整数。

异常:如果值a小于MinValue或大于MaxValue,则此方法将给出OverflowException。

下面的程序说明了Decimal.ToByte(Decimal)方法的用法:

范例1:

// C# program to demonstrate the
// Decimal.ToByte(Decimal) Method
using System;
using System.Globalization;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
        try {
  
            // Declaring the decimal variable
            Decimal a = 127.97m;
  
            // using ToByte() method;
            byte value = Decimal.ToByte(a);
  
            // Display the byte value
            Console.WriteLine("The Byte value "+
                             "is : {0}", value);
        }
  
        catch (OverflowException e) 
        {
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
}
输出:
The Byte value is : 127

范例2:

// C# program to demonstrate the
// Decimal.ToByte(Decimal) Method
using System;
using System.Globalization;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
        try {
  
            // Declaring the decimal variable
            Decimal a = -0.999m;
  
            // using ToByte() method;
            byte value = Decimal.ToByte(a);
  
            // Display the byte value
            Console.WriteLine("The Byte value"+
                           " is : {0}", value);
        }
  
        catch (OverflowException e) 
        {
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
}
输出:
The Byte value is : 0

示例3: OverflowException程序

// C# program to demonstrate the
// Decimal.ToByte(Decimal) Method
using System;
using System.Globalization;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
        try {
  
            // Declaring the decimal variable
            Decimal a = -98.45m;
  
            // using ToByte() method;
            byte value = Decimal.ToByte(a);
  
            // Display the byte value
            Console.WriteLine("The Byte value "+
                             "is : {0}", value);
        }
  
        catch (OverflowException e) 
        {
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
}
输出:
Exception Thrown: System.OverflowException

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.decimal.tobyte?view=netframework-4.7.2