2012-05-24 16 views
0

回報語法我不知道爲什麼我需要把返回語法兩倍的時間在下面的代碼,約在C#

public string test(){ 
bool a = true; 
if(a){ 
    string result = "A is true"; 
}else{ 
    string result = "A is not true"; 
} 

    return result; 
} 

它叫說出姓名「結果」並不在當前的背景下存在的錯誤。

但無論哪種方式,都有結果變量。嗯..

所以我改變了這樣的代碼,

public string test(){ 
bool a = true; 
if(a){ 
    string result = "A is true"; 
    return result; 
}else{ 
    string result = "A is not true"; 
    return result; 
} 
} 

然後,它的工作原理。這樣使用是否正確?

請指教我,

謝謝!

+4

我非常懷疑你的第二個代碼*實際*工作。你還沒有在任何時候聲明變量'result'。請注意,這與ASP.NET沒有任何關係 - 它只是C#。 –

+0

你說「那麼它的工作原理」,但即使你的第二段代碼是無效的C#,除非在別處聲明瞭'result'。你確定它有效嗎? –

回答

7

你只是缺少result聲明中的代碼塊..我個人呢(除非當修正),但在這裏建議的第二個代碼塊...

public string test(){ 
bool a = true; 
string result = string.Empty; 
if(a){ 
    result = "A is true"; 
}else{ 
    result = "A is not true"; 
} 

    return result; 
} 

如果你打算去與第二塊您可以將其簡化爲:

public string test(){ 
bool a = true; 
if(a){ 
    return "A is true"; 
}else{ 
    return "A is not true"; 
} 
} 

或進一步到:

public string test(){ 
bool a = true; 

return a ? "A is true" : "A is not true"; 
} 

和其他幾個類似代碼的迭代(字符串格式等)。

+1

你甚至不需要初始化'result'。 – Joey