Web服务需要返回一个数组,但不返回任何内容

本文关键字:返回 数组 任何内 一个 服务 Web | 更新日期: 2023-09-27 18:27:46

我正在编写我的第一个web服务,似乎遇到了一些问题。我返回一个结果没有任何问题,但当我试图返回一个自定义类对象数组时,却一无所获。我在这里做错了什么?

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/"/>

Web服务需要返回一个数组,但不返回任何内容

假设您从数据库中获得结果,则忘记在数组内部创建新实例:

...
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();
}
...