簡體   English   中英

為什么使用decimal(int [])構造函數?

[英]Why use decimal(int [ ]) constructor?

我在Windows 7上使用Visual Studio 2013維護一個C#桌面應用程序。在代碼中的某處有以下行,它嘗試使用Decimal(Int32 [])構造函數創建一個0.01的十進制值:

decimal d = new decimal(new int[] { 1, 0, 0, 131072 });

第一個問題是,它與以下不同嗎?

decimal d = 0.01M;

如果沒有什么不同,開發人員為什么會遇到這樣編碼的麻煩?

我需要更改此行以創建動態值。 就像是:

decimal d = (decimal) (1 / Math.Pow(10, digitNumber));

我會以這種方式引起一些不受歡迎的行為嗎?

當小數點的來源由位組成時,對我來說似乎很有用。

.NET中使用的十進制有一個基於一系列位參數的實現(不僅僅是一個像int一樣的位流),所以當你與其他返回的系統進行通信時,用位構造一個十進制數是很有用的。通過一串字節(一個套接字,一塊內存等)的十進制數。

現在很容易將位組轉換為小數。 無需花哨的轉換代碼。 此外,您可以根據標准中定義的輸入構造小數,這樣便於測試.NET框架。

decimal(int[] bits)構造函數允許您給出要創建的小數的按位定義位必須是4 int數組,其中:

位0,1和2構成96位整數。

位3包含比例因子和符號

它只是讓你從你的例子中得到十分精確的十進制定義,我認為你不需要那么高的精度。

有關使用該構造函數的更多詳細信息,請參閱此處 ,或者此處查看可能更適合您的其他構造函數

如果digitNumber是16位指數則更具體地回答你的問題,那么decimal d = new decimal(new int[] { 1, 0, 0, digitNumber << 16 }); 做你想要的,因為指數進入數組中最后一個int的第16-23位

xml中的定義是

    //
    // Summary:
    //     Initializes a new instance of System.Decimal to a decimal value represented
    //     in binary and contained in a specified array.
    //
    // Parameters:
    //   bits:
    //     An array of 32-bit signed integers containing a representation of a decimal
    //     value.
    //
    // Exceptions:
    //   System.ArgumentNullException:
    //     bits is null.
    //
    //   System.ArgumentException:
    //     The length of the bits is not 4.-or- The representation of the decimal value
    //     in bits is not valid.

因此,原始開發人員想要以這種方式初始化他的小數。 也許他只是想在將來混淆某人。

如果將其更改為,則無法影響您的代碼

decimal d = 0.01m;

因為

(new decimal(new int[] { 1, 0, 0, 131072})) == 0.01m

你應該知道如何將十進制存儲在內存中。

您可以使用此方法生成所需的值

public static decimal Base10FractionGenerator(int digits)
{
    if (digits < 0 || digits > 28)
        throw new ArgumentException($"'{nameof(digits)}' must be between 0 and 28");

    return new decimal(new[] { 1, 0, 0, digits << 16 });
}

像它一樣使用它

Console.WriteLine(Base10FractionGenerator(0));
Console.WriteLine(Base10FractionGenerator(2));
Console.WriteLine(Base10FractionGenerator(5));

這是結果

1
0.01
0.00001

您正在討論的特定構造函數從四個32位值生成一個小數。 遺憾的是,較新版本的公共語言基礎結構(CLI)未指定其確切格式(可能是為了允許實現支持不同的十進制格式),現在僅保證至少一個特定的精度和十進制數范圍。 但是,早期版本的CLI確實像Microsoft的實現那樣定義了這種格式,因此它可能在Microsoft的實現中保持這種方式以實現向后兼容。 但是,並不排除CLI的其他實現將以不同方式解釋Decimal構造函數的四個32位值。

小數是精確的數字,你可以使用==或!=來測試相等性。

也許,這行代碼來自某個特定時間點有意義的其他地方。

我要清理它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM