【问题标题】:c# not all code paths return a value errorc#并非所有代码路径都返回值错误
【发布时间】:2013-07-12 13:49:45
【问题描述】:

使用此代码在 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");
    }
}                     

【问题讨论】:

  • 我想你可能想重命名你的Variable var。 var 是一些最新版本的 C# 中的保留关键字。
  • 不要忘记在函数结束时返回值

标签: c# .net function stringbuilder


【解决方案1】:

你忘记在那里返回值:

 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
    }

您还应该在函数结束时返回值。

【讨论】:

  • 谢谢 :) 我不敢相信我没有看到!
  • @Gabe 而不是感谢每一个人。只需标记解决您问题的答案
  • @im_a_noob 抱歉,我不得不等了十分钟,然后我不得不去某个地方,所以我现在才回来:P
  • @Gabe 这么说很酷,因为很多新用户没有标记答案
【解决方案2】:

如果:

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;
}

【讨论】:

  • 谢谢 :) 我不敢相信我没有看到!
【解决方案3】:

其中的任何一项如何工作?您的方法返回类型 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;
}

您也应该在此方法的末尾添加一个 return。

【讨论】:

  • 很可能StringLiteralIntLiteralVariable 都是Expr 的子类,所以实际上这应该可以工作。
  • 是的,我已经猜到了很多,但是如果是这种情况,代码可以很多更具可读性。
猜你喜欢
  • 2023-03-20
  • 1970-01-01
  • 1970-01-01
  • 2013-07-01
  • 2014-04-16
  • 2015-02-07
  • 2012-04-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多