2013-07-12 35 views
1

我在這個代碼在c#中得到以下錯誤 「並非所有的代碼路徑返回一個值」 我想創建一個使用它的編程語言。 任何幫助,非常感謝。c#不是所有的代碼路徑返回一個值錯誤

private Expr ParseExpr() 
{ 
    if (this.index == this.tokens.Count) 
    { 
     throw new System.Exception("expected expression, got EOF"); 
    } 
    if (this.tokens[this.index] is Text.StringBuilder) 
    { 
     string Value = ((Text.StringBuilder)this.tokens[this.index++]).ToString(); 
     StringLiteral StringLiteral = new StringLiteral(); 
     StringLiteral.Value = Value; 
    } 
    else if (this.tokens[this.index] is int) 
    { 
     int intvalue = (int)this.tokens[this.index++]; 
     IntLiteral intliteral = new IntLiteral(); 
     intliteral.Value = intvalue; 
     return intliteral;  
    } 
    else if (this.tokens[this.index] is string) 
    { 
     string Ident = (string)this.tokens[this.index++]; 
     Variable var = new Variable(); 
     var.Ident = Ident; 
     return var; 
    } 
    else 
    { 
     throw new System.Exception("expected string literal, int literal, or variable"); 
    } 
}      
+1

我想你可能想重命名你的'Variable var'。 var是C#的一些最新版本中的保留關鍵字。 – Katana314

+1

不要忘記在函數結束時返回值 – Andrei

回答

9

你忘了有返回值:

if (this.tokens[this.index] is Text.StringBuilder) 
    { 
     string Value = ((Text.StringBuilder)this.tokens[this.index++]).ToString(); 
     StringLiteral StringLiteral = new StringLiteral(); 
     StringLiteral.Value = Value; 
     //return Anything 
    } 

你還應該在你的函數的最後返回值。

+1

謝謝:)我不相信我沒有看到! – Gabe

+2

所以我:) ...... – Andrei

+1

@加布而不是對每一個人表示感謝。只需標記修復您的問題的答案 –

5

你忘了在第二返回任何東西,如果:

if (this.tokens[this.index] is Text.StringBuilder) 
{ 
    string Value = ((Text.StringBuilder)this.tokens[this.index++]).ToString(); 
    StringLiteral StringLiteral = new StringLiteral(); 
    StringLiteral.Value = Value; 
    return StringLiteral; 
} 
+0

謝謝:)我不相信我沒有看到! – Gabe

4

哪有什麼是工作?你的方法返回一個類型Expr,但你在每個if語句中返回不同的類型。

的問題是,你少在此塊return

if (this.tokens[this.index] is Text.StringBuilder) 
{ 
    string Value = ((Text.StringBuilder)this.tokens[this.index++]).ToString(); 
    StringLiteral StringLiteral = new StringLiteral(); 
    StringLiteral.Value = Value; 
    return Value; 
} 

你應該在這個方法的末尾添加回報了。

+0

最有可能的'StringLiteral','IntLiteral'和'Variable'都是'Expr'的所有子類,所以實際上這應該起作用。 – Andrei

+0

是的,我猜到了,但是如果情況是這樣的話,代碼可以變得更加可讀。 – DGibbs

+0

抱歉,我是一個新手:P – Gabe

相關問題