Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

เมธอด Decimal.Negate ใน C# พร้อมตัวอย่าง


บทนำ

เมธอด Decimal.Negate() ใน C# ใช้สำหรับคืนค่าผลคูณของค่า Decimal ที่ระบุด้วย -1 (ค่าลบ) กล่าวคือ เปลี่ยนเครื่องหมายของค่าจากบวกเป็นลบ หรือจากลบเป็นบวก

ไวยากรณ์ (Syntax)

public static decimal Negate (decimal val);

โดยที่ val คือค่าที่ต้องการเปลี่ยนเครื่องหมาย

ตัวอย่างที่ 1: เปลี่ยนจากค่าบวกเป็นลบ

using System;

public class Demo 
{
    public static void Main()
    {
        Decimal val = 3972.491m;
        
        Console.WriteLine("Decimal Value = {0}", val);
        Console.WriteLine("HashCode = {0}", val.GetHashCode());
        
        TypeCode type = val.GetTypeCode();
        Console.WriteLine("TypeCode = " + type);
        
        Decimal res = Decimal.Negate(val);
        Console.WriteLine("Negative (Decimal) = " + res);
    }
}

ผลลัพธ์

Decimal Value = 3972.491
HashCode = 620041307
TypeCode = Decimal
Negative (Decimal) = -3972.491

ตัวอย่างที่ 2: เปลี่ยนจากค่าลบเป็นบวก

using System;

public class Demo 
{
    public static void Main()
    {
        Decimal val = -29.35m;
        
        Console.WriteLine("Decimal Value = {0}", val);
        Console.WriteLine("HashCode = {0}", val.GetHashCode());
        
        TypeCode type = val.GetTypeCode();
        Console.WriteLine("TypeCode = " + type);
        
        Decimal res = Decimal.Negate(val);
        Console.WriteLine("Negative (Decimal) = " + res);
    }
}

ผลลัพธ์

Decimal Value = -29.35
HashCode = 1503969289
TypeCode = Decimal
Negative (Decimal) = 29.35

สรุป

เมธอด Decimal.Negate() ให้วิธีที่ชัดเจนและอ่านง่ายในการกลับเครื่องหมายค่า Decimal ซึ่งเทียบเท่ากับการคูณด้วย -1 แต่สื่อความหมายของโค้ดได้ดียิ่งขึ้น