2016-07-05 58 views
-2

我不能在該方法使用相同的參數DetermineCarValue我不能在方法中使用相同的參數。 CS0136

public static decimal DetermineCarValue(Car carValue) 
     { 
      decimal carValue = 100.0M; 
      return carValue; 
     } 

當我鍵入carValue參數我得到這個錯誤

CS0136 A local or parameter named 'carValue' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter 
+7

錯誤不是很明顯嗎? – haim770

+4

你有'carValue'作爲'Car'類型的參數和''decimal'類型的本地。你必須爲其中一個選擇一個不同的名字。 –

+0

你是說在粘貼到問題框之前,你甚至沒有閱讀錯誤信息? –

回答

10

你回答了自己的問題:

我不能在方法中使用相同的參數DetermineCarValue

將本地方法變量carValue重命名爲其他內容。

你有兩個相同名稱的變量,一個傳遞給方法,另一個在方法中聲明。

public static decimal DetermineCarValue(Car carValue) 
{ 
    decimal carValue = 100.0M; 
    return carValue; // which carValue ? of type Car or decimal ? Confusing 
} 

我真的不知道這種方法是應該做的,但如果你的意思是更新Car對象的某些屬性,那麼你可以這樣做:

public static decimal DetermineCarValue(Car car) 
{ 
    // suppose you have property called Value in your Car class 
    car.Value = 100.0M; 
    return car.Value; 
} 

結論:

不能聲明一個方法變量與方法參數具有相同的名稱。更確切地說,在同一範圍內不能有兩個同名的標識符。

4

我將解釋你遇到的編譯器錯誤,以防它對你不明顯。

您用於Car類型參數的標識符與您在同一範圍內聲明的十進制類型變量所使用的標識符相同,該範圍僅限於您的方法。這會引起歧義,並使編譯器無法確定您所指的是哪個變量。要解決此問題,請重命名參數或定義的變量。

如果您想重載變量carValue,請注意它不受支持。

相關問題