Service.datalist无法序列化,因为它没有无参数构造函数

时间:2014-06-15 07:16:49

标签: c#

我正在写一个网络方法:

[WebMethod]
public List<datalist7> getsaba(string accno, string fromdate, string todate)
{
    SqlConnection con = new SqlConnection(@"Data Source=123-PC;Initial Catalog=bcounts;Persist Security Info=True;User ID=Saba;Password=123");
    con.Open();
    SqlCommand cmd = new SqlCommand("select gt.Value_Date,gt.Voucher_no+'-'+gr.VchrType as voucher,gt.Acct_Nirration,gr.InstrumentNo,gt.Dr_Amount,gt.Cr_Amount  from gl_transaction gt, Gl_Ref gr where gt.Accountno = '" + accno + "'  and gt.Voucher_No=gr.Voucher_no  and gt.Value_Date between '" + fromdate + "' and '" + todate + "'", con);
    SqlDataReader rdr = cmd.ExecuteReader();
    decimal crsum = 0;
    decimal drsum = 0;
    decimal balance = 0;

    List<datalist7> data = new List<datalist7>();

    if (rdr.HasRows)
    {
        while (rdr.Read())
        {
            if (rdr.GetDecimal(4) > 0)
            {
                balance = balance + rdr.GetDecimal(4);
                drsum += rdr.GetDecimal(4);
                data.Add(new datalist7(rdr.GetDateTime(0).ToShortDateString(), rdr.GetString(1), rdr.GetString(2), rdr.GetString(3), rdr.GetDecimal(4).ToString(), "-", balance.ToString()));
            }
            else
            {
                balance = balance - rdr.GetDecimal(5);
                crsum += rdr.GetDecimal(5);
                data.Add(new datalist7(rdr.GetDateTime(0).ToShortDateString(), rdr.GetString(1), rdr.GetString(2), rdr.GetString(3), "-", rdr.GetDecimal(5).ToString(), balance.ToString()));
            }
        }
        data.Add(new datalist7("-", "-", "-", "-", drsum.ToString(), crsum.ToString(), "-"));
    }

    con.Close();
    return data;
}

[DataContract]
public class datalist7
{
    [DataMember]
    public string val1 { get; set; }
    [DataMember]
    public string val2 { get; set; }
    [DataMember]
    public string val3 { get; set; }
    [DataMember]
    public string val4 { get; set; }
    [DataMember]
    public string val5 { get; set; }
    [DataMember]
    public string val6 { get; set; }
    [DataMember]
    public string val7 { get; set; }

    public datalist7(string v1, string v2, string v3, string v4, string v5, string v6, string v7)
    {
        val1 = v1;
        val2 = v2;
        val3 = v3;
        val4 = v4;
        val5 = v5;
        val6 = v6;
        val7 = v7;
    }
}

在ASMX,但我收到一个错误:

  

Service.datalist7无法序列化,因为它没有无参数构造函数。

如何解决?

2 个答案:

答案 0 :(得分:1)

如果你看一下这个问题的答案:Why XML-Serializable class need a parameterless constructor它解释了为什么序列化的类需要一个无参数的构造函数。

您可以删除构造函数并实例化对象,如下所示:

data.Add(new datalist7() { val1 = "-", val2 = "-", val3 = "-", val4 = "-", val5 = drsum.ToString(), val6 = crsum.ToString(), val7 = "-" });

答案 1 :(得分:0)

将此添加到datalist7类。它是一个默认构造函数。

public datalist7() { }