我正在编写我的第一个Web服务,似乎遇到了一些问题。我在返回单个结果时没有任何问题但是当我尝试返回自定义类对象的数组时,我什么都没得到。我在这里做错了什么?
网络服务
public class Service1 : System.Web.Services.WebService
{
private string strCrossoverConnection = "Connection String";
[WebMethod]
public CompetitorMatch[] GetCloseCompetitorMatches(string partNumber, string member)
{
using (SqlConnection con = new SqlConnection(strCrossoverConnection))
using (SqlCommand cmd = new SqlCommand("[SelectClosestMatch]", con))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandTimeout = 6000;
cmd.Parameters.AddWithValue("@SimplePart", partNumber);
cmd.Parameters.AddWithValue("@CurrentMember", member);
cmd.Parameters.AddWithValue("@isClosestMatch", 1);
cmd.Parameters.AddWithValue("@isQuickSearch", 0);
CompetitorMatch[] competitorPartMatches = null;
con.Open();
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
da.Fill(dt);
int resultCount = dt.Rows.Count;
if (resultCount > 0)
{
competitorPartMatches = new CompetitorMatch[resultCount ];
for (int i = 0; i < resultCount; i++)
{
competitorPartMatches[i].PartNumber = dt.Rows[i]["Part Number"].ToString();
}
}
}
return competitorPartMatches;
}
}
public class CompetitorMatch
{
private string m_partNumber;
public CompetitorMatch() { }
public CompetitorMatch(string partNumber){
partNumber = PartNumber;
}
public string PartNumber { get { return m_partNumber; } set { m_partNumber = value; } }
}
}
返回:
<CompetitorMatch xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://codeproject.com/webservices/"/>
答案 0 :(得分:1)
假设您从数据库中获取结果,您将忘记为数组内部创建新实例:
...
competitorPartMatches = new CompetitorMatch[resultCount];
for (int i = 0; i < resultCount; i++)
{
competitorPartMatches[i] = new CompetitorMatch(); // <-- CREATE NEW INSTANCE!
competitorPartMatches[i].PartNumber = dt.Rows[i]["Part Number"].ToString();
}
...