提问人:Jeff Collombet 提问时间:12/20/2022 最后编辑:dbcJeff Collombet 更新时间:12/20/2022 访问量:110
在 WCF 服务中返回字符串数组
Return an Array of string in a WCF Service
问:
您好,在 C# WCF 服务应用程序中,我想在方法中返回一个包含 5 个字符串的数组。上面的代码没有返回任何错误,但是当我在调试模式下启动服务时,它只显示数组上的第一个字符串。
这是 IService 方面:
[OperationContract]
string[] NaviresXml();
这是服务方面:
public string[] NaviresXml()
{
try
{
XMLReader x = new XMLReader(FilePath);
return new string[] { x.ReadXmlDocument_Navires() };
}
catch (Exception ex)
{
throw new Exception(ex.Message + "\n" + ex.StackTrace);
}
}
和 XMLReader 类:
public class XMLReader
{
public string XmlFilePath { get; set; }
public XMLReader(string XmlFilePath)
{
this.XmlFilePath = XmlFilePath;
}
public string ReadXmlDocument_Navires()
{
XmlDocument xmlDoc1 = new XmlDocument();
xmlDoc1.Load(XmlFilePath);
XmlNodeList itemNodes = xmlDoc1.GetElementsByTagName("Navire");
if (itemNodes.Count > 0)
{
foreach (XmlElement node in itemNodes)
return "Navire" + node.Attributes["Type"].Value + "Nom" + node.Attributes["Nom"].Value;
}
return null;
}
}
当我启动服务时,我只能看到第一个字符串,而看不到其他字符串。在此处输入图像描述
这个代码有什么问题?
我试图在没有 XMLReader 类的情况下做到这一点,并将代码直接放在服务端,但这没有用。
答:
0赞
Kurubaran
12/20/2022
#1
将 return 语句移出循环。
StringBuilder stringContent = new StringBuilder();
if (itemNodes.Count > 0)
{
foreach (XmlElement node in itemNodes)
stringContent.Append("Navire" + node.Attributes["Type"].Value + "Nom" + node.Attributes["Nom"].Value);
}
return stringContent.ToString();
0赞
Jiayao
12/20/2022
#2
执行 return 语句时,函数执行将停止并跳出正在执行的函数,即使函数主体中还有其他语句也是如此。返回后的代码不执行。
所以你需要像这样把返回值放在循环之外:
public class XMLReader
{
public string XmlFilePath { get; set; }
public XMLReader(string XmlFilePath)
{
this.XmlFilePath = XmlFilePath;
}
public string ReadXmlDocument_Navires()
{
XmlDocument xmlDoc1 = new XmlDocument();
xmlDoc1.Load(XmlFilePath);
XmlNodeList itemNodes = xmlDoc1.GetElementsByTagName("Navire");
StringBuilder res = new StringBuilder();
if (itemNodes.Count > 0)
{
foreach (XmlElement node in itemNodes)
res.append("Navire" + node.Attributes["Type"].Value + "Nom" + node.Attributes["Nom"].Value);
}
return res.ToString();
}
return null;
}
评论