2017-04-12 76 views
-3
private decimal? xposition; 
public decimal? XPosition 
{ 
    get 
    { 
     return this.xposition; 
    } 
    set 
    { 
     this.xposition = value; 
     Math.Round(this.xposition, 4); 
    } 
} 

爲什麼我不能在set方法中使用Math.round?它說:爲什麼我不能在set方法中使用Math.round#

參數'#1'不能轉換'小數?'表達式爲'double'

+1

請問您可以粘貼相關代碼嗎? – Bathsheba

+0

私有小數? xPosition位置; –

+0

私有小數? xPosition位置; \t \t public decimal? x向位置 \t \t { \t \t \t得到 \t \t \t { \t \t \t \t回報this.xposition; \t \t \t} \t \t \t設置 \t \t \t \t {\t \t \t \t \t \t \t this.xposition =值; \t \t \t \t Math.Round(this.xposition,4); \t \t \t \t} \t \t \t \t} –

回答

3

Math.Round使用十進制,不可爲空的十進制。改爲使用Math.Round(xposition.Value, 4)。此外,請注意,必須將此值分配爲有用,也許您的意思是做類似的操作:

private decimal? xposition; 
public decimal? XPosition 
{ 
    get 
    { 
     return this.xposition; 
    } 
    set 
    { 
     this.xposition = value.HasValue ? Math.Round(value.Value, 4) : null; 
    } 
} 
+0

你在setter中有一個額外的分號。 – vyrp

+0

這不是@vyrp的問題。不檢查null是。 –

+0

是的,我知道。其他答案更正確。我只是想清理雙分號。但我無法編輯,因爲它的變化不會超過6個字符。 – vyrp

0

您的代碼有幾個問題。

  • 首先,您應該使用可空decimal.Value
  • 其次,在使用它之前,您應該檢查該值是否爲null
  • 第三,你應該分配結果。

我會使用此代碼:

private decimal? xposition; 
public decimal? XPosition 
{ 
    get 
    { 
     return this.xposition; 
    } 
    set 
    { 
     if (value != null) 
     { 
      this.xposition = Math.Round(value.Value, 4); 
     } 
     else 
     { 
      this.xposition = value; 
     } 
    } 
} 
2

Math.Round傳回四捨五入值,它不會修改傳遞的值。所以,你必須返回值分配給支持字段xposition

xposition = Math.Round(value, 4); 

但因爲它是一個可空,你必須處理它可以爲空的情況下,你必須將它轉換爲十進制爲Math.Round

public decimal? XPosition 
{ 
    get 
    { 
     return this.xposition; 
    } 

    set 
    { 
     this.xposition = value == null ? (decimal?)null : Math.Round(value.Value, 4); 
    } 
} 
相關問題