2010-02-12 67 views
0

我不確定它是否只是我,但這似乎有點不可思議。我有一個靜態類中的一些擴展舍入值:擴展和十進制和雙之間的衝突

public static double? Round(this double? d, int decimals) 
    { 
     if (d.HasValue) 
      return Math.Round(d.Value, decimals, MidpointRounding.AwayFromZero); 
     return null; 
    } 
    public static double? Round(this double d, int decimals) 
    { 
     return Math.Round(d, decimals, MidpointRounding.AwayFromZero); 
    } 

我最近增加了同爲四捨五入小數:

public static decimal? Round(this decimal? d, int decimals) 
    { 
     if (d.HasValue) 
      return Math.Round(d.Value, decimals, MidpointRounding.AwayFromZero); 
     return null; 
    } 
    public static decimal? Round(this decimal d, int decimals) 
    { 
     return Math.Round(d, decimals, MidpointRounding.AwayFromZero); 
    } 

我希望沒有人能看到什麼錯,在這一點上。當我的代碼

 var x = (decimal)0; 
     var xx = x.Round(0); 

的CLR引發錯誤會員「decimal.Round(十進制)」不能以一個實例引用來訪問它出現;用類型名稱代替它

WTF?如果我只是重命名我的小數四捨五入擴展(例如稱爲RoundDecimal),一切工作正常。似乎CLR不知何故混淆了雙精度和十進制方法..任何人都可以解釋這一點嗎?

有趣的是,如果我叫圓(X,0)代替,它工作正常...

回答

3

當你撥打:

var xx = x.Round(0); 

編譯器認爲這是給Decimal.Round一個電話,這是一個錯誤,因爲它是一個靜態的。

我強烈建議爲您的方法使用不同於框架「圓」方法的名稱。例如,你的情況,我建議使用RoundAwayFromZero。如果你這樣做,你可以這樣做:

var xx = x.RoundAwayFromZero(0);