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

📅  最后修改于: 2021-05-30 00:45:32             🧑  作者: Mango

此方法用于将两个指定的十进制值相加。

例外:如果a1和a2的总和小于Decimal的最小可能值大于Decimal的最大可能值,则此方法将给出OverflowException

下面的程序说明了Decimal.Add(Decimal,Decimal)方法的用法

范例1:

// C# program to demonstrate the
// Decimal.Add(Decimal, Decimal) 
// Method
using System;
using System.Globalization;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
        try {
  
            // Declaring the decimal
            // variables
            Decimal a1 = .01m;
            Decimal a2 = .03m;
  
            // adding the two Decimal value
            // using Add() method;
            Decimal value = Decimal.Add(a1, a2);
  
            // Display the sum
            Console.WriteLine("Decimal Sum : {0}",
                                           value);
        }
  
        catch (OverflowException e) 
        {
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
}
输出:
Decimal Sum : 0.04

示例2:对于OverflowException

// C# program to demonstrate the
// Decimal.Add(Decimal, Decimal)
// Method
using System;
using System.Globalization;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
        try {
  
            // Declaring the decimal variables
            Decimal a1 = 1.01m;
            Decimal a2 = Decimal.MaxValue;
  
            // adding the two Decimal value
            // using Add() method;
            Decimal value = Decimal.Add(a1, a2);
  
            // Display the sum
            Console.WriteLine("Decimal Sum : {0}",
                                           value);
        }
  
        catch (OverflowException e) 
        {
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
}
输出:
Exception Thrown: System.OverflowException