C# 由于 '{method}' 返回 void,return 关键字后不能跟对象表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16450660/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Since '{method}' returns void, a return keyword must not be followed by an object expression
提问by Waverunner
I'm trying to return a simple string from an XML file when you call a method after defining the location of the XML file. However, when I try to return, it says that "Since 'CareerDescription()' returns void, a return keyword must not be followed by an object expression". The word return is highlighted red and that's the message. Compiler will say "Method must have a return type". I do have the return type but it doesn't want to return... Here is the code:
当您在定义 XML 文件的位置后调用方法时,我试图从 XML 文件返回一个简单的字符串。但是,当我尝试返回时,它说“由于 'CareerDescription()' 返回 void,返回关键字后不能跟对象表达式”。返回一词以红色突出显示,这就是消息。编译器会说“方法必须有一个返回类型”。我确实有返回类型,但它不想返回......这是代码:
public CareerDescription(string CareerFile)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(CareerFile);
string Description = xmlDoc.SelectSingleNode("Careers/CareerList/CareerDescription").InnerText;
return Description;
}
I also tried this to see if it was something wrong with the method I created, however I get the same exact error message....
我也试过这个,看看我创建的方法是否有问题,但是我得到了完全相同的错误消息......
public TestMethod()
{
string test = "test";
if (test == "test")
{
return test;
}
}
And this also gives the same message...
这也给出了同样的信息......
public TestMethod()
{
string test = "test";
return test;
}
What am I doing wrong in the creation of my methods? I can't for the life of me figure it out...
我在创建方法时做错了什么?我一辈子都搞不清楚...
采纳答案by D Stanley
Add a return type
添加返回类型
V----V
public string CareerDescription(string CareerFile)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(CareerFile);
string Description = xmlDoc.SelectSingleNode("Careers/CareerList/CareerDescription").InnerText;
return Description;
}
A method MUST have a return type, so I'm curious what is telling you this:
一个方法必须有一个返回类型,所以我很好奇是什么告诉你这个:
"Since 'CareerDescription()' returns void, a return keyword must not be followed by an object expression".
“由于 'CareerDescription()' 返回 void,返回关键字后不能跟对象表达式”。
when you omit a return type, as the TRUE error is not the return, but the LACK of a return type.
当您省略返回类型时,因为 TRUE 错误不是return,而是返回类型的 LACK。
For example this is not legal:
例如,这是不合法的:
public DoNothing()
{
return;
}

