2012-02-04 55 views
6

我不得不處理用大號碼進行計算的代碼,例如,long integer literals

long foo = 6235449243234; 

這很難說是什麼數量級。我希望把它寫

long foo = 6_235_449_243_234; 

或者

long foo = @6 235 449 243 234; 

但是C#不具備這些功能。如何讓數字文字更具可讀性?

評論

long foo = 6235449243234; // 6 23... 

從字符串

long foo = LiteralConverter.toLong(@"6_235_449_243_234"); 
int mask = LiteralConverter.toInt("b0111_0000_0100_0000"); 

任何其他選項轉換呢?

+2

的可能重複(http://stackoverflow.com/questions/8488989/can -i-declare-constant-integers -with-a-thousand-separator-in-c) – CodesInChaos 2012-02-04 19:04:52

+0

在'LiteralConverter.toLong'示例中,'@'不是必需的。 – luiscubal 2012-02-04 19:05:48

+0

該語言應該支持在數字文字中使用'_'。我沒有看到解析器無法支持的原因。 – 2015-10-23 09:24:14

回答

3

每次IMO評論。否則,你只是使代碼不是最佳臃腫,少:

long foo = 6235449243234; // 6,235,449,243,234 
1

評論 - 如果可能的話 - 採用conststatic readonly值,這樣你只申報/在一個地方評論數。

5

爲這些文字定義命名常量,並使用註釋來解釋數字代表的內容。

class MyClass { 
    /// 
    /// This constant represents cost of a breakfast in Zimbabwe: 
    /// 6,235,449,243,234 
    /// 
    const long AvgBreakfastPriceZimbabweanDollars = 6235449243234; 
} 
+4

+1,但早餐的價格可能已經翻了一番。 – Marlon 2012-02-04 19:24:39

3

你可以寫

long lNumber = (long)(6e12 + 235e9 + 449e6 + 243e3 + 234); 

但是,這是不是真的讀無論是。

對於調試時變量中的數字,您可以編寫一個debugger visualizer

+0

+1調試器可視化器,不知道它 – 2012-02-04 19:11:49

1

這樣做的另一個(不推薦)的方式:[?我可以聲明,在C#中的千位分隔符常量整數]

static long Parse(params int[] parts) 
{ 
    long num = 0; 
    foreach (int part in parts) 
     num = num * 1000 + part; 
    return num; 
} 

long foo = Parse(6,235,449,243,234); 
+0

很聰明(盒子外面) – 2014-01-30 05:38:23