【问题标题】:Since '{method}' returns void, a return keyword must not be followed by an object expression [closed]由于'{method}'返回void,return关键字后面不能跟对象表达式[关闭]
【发布时间】:2013-05-03 06:32:54
【问题描述】:

当您在定义 XML 文件的位置后调用方法时,我试图从 XML 文件返回一个简单的字符串。但是,当我尝试返回时,它说“由于 'CareerDescription()' 返回 void,return 关键字后面不能跟对象表达式”。返回这个词以红色突出显示,这就是信息。编译器会说“方法必须有返回类型”。我确实有返回类型,但它不想返回......这是代码:

    public CareerDescription(string CareerFile)
    {
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(CareerFile);
        string Description = xmlDoc.SelectSingleNode("Careers/CareerList/CareerDescription").InnerText;
        return Description;
    }

我也试过这个,看看我创建的方法是否有问题,但是我得到了同样的错误信息......

    public TestMethod()
    {
        string test = "test";
        if (test == "test")
        {
            return test;
        }
    }

这也给出了同样的信息......

    public TestMethod()
    {
        string test = "test";
        return test;
    }

我在创建方法时做错了什么?我这辈子都想不通...

【问题讨论】:

  • 首先,你的“方法”要么是构造函数,要么是编译器错误,你没有指定它们的返回类型。

标签: c# methods .net-4.0 compiler-errors return


【解决方案1】:

添加返回类型

       V----V
public string CareerDescription(string CareerFile)
{
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.Load(CareerFile);
    string Description = xmlDoc.SelectSingleNode("Careers/CareerList/CareerDescription").InnerText;
    return Description;
}

一个方法必须有一个返回类型,所以我很好奇这是在告诉你什么:

“由于 'CareerDescription()' 返回 void,return 关键字后面不能跟对象表达式”。

当您省略返回类型时,因为 TRUE 错误不是 return,而是返回类型的 LACK。

例如这是不合法的:

public DoNothing()
{
    return;
}

【讨论】:

  • 刚刚添加到字符串中,它工作得很好。非常感谢,也感谢您的解释,帮助很大。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-04
  • 2021-07-15
  • 1970-01-01
  • 2013-06-04
相关资源
最近更新 更多