0

我有类 SellStatement

public class SellStatement
{
    public long billNo
    public DateTime paymentDate;
    public List<string>  ProductName;
    public List<double> quantity;
    public List<double> ratePerQuantity;
}

当我尝试访问函数 GetSaleDetails

public Exception GetSaleDetails(List<SellStatement> lss1,string query)
    {
        try
        {
            for (int i = 0; i < lss1.ToArray().Length; i++)
            {
                query = "select * from [product details] where [bill no]=@billno";
                com = new SqlCeCommand(query, con);
                con.Open();
                com.Parameters.AddWithValue("@billno",lss1[i].billNo);
                sdr = com.ExecuteReader();
                while (sdr.Read())
                {
                    lss1[i].ProductName.Add(sdr.GetString(1));//Exception line
                    lss1[i].quantity.Add(sdr.GetDouble(2));
                    lss1[i].ratePerQuantity.Add(sdr.GetDouble(3));       
                }
            }
            con.Close();
            return null;
        }
        catch (Exception e)
        {
            con.Close();
            return e;
        }
    }

Null Reference Exception 出现在lss1[i].ProductName.Add(sdr.GetString(1));。我认为错误可能是由于 at 中的 null 值,sdr.GetString(1)但我检查了它有一些值。我的朋友告诉我,你不能像这样更改 Function 参数值,所以我尝试将一个列表复制到另一个像这样 。

 List<SellStatement> lss1 = new List<SellStatement>() ;
            lss1.AddRange(lss);

但这对我没有帮助。添加元素时我无法弄清楚出了什么问题。

4

1 回答 1

4

如果您SellStatement在问题中向我们展示了您的完整课程,那么原因很清楚:
您从未初始化ProductName,quantityratePerQuantity. 它们是null,这正是异常告诉你的。

要修复它,请将您的课程更改为:

public class SellStatement
{
    public long billNo
    public DateTime paymentDate;
    public List<string> ProductName = new List<string>();
    public List<double> quantity = new List<double>();
    public List<double> ratePerQuantity = new List<double>();
}

请注意,这违反了正常的 C# 设计指南,即您不应该拥有公共字段。考虑像这样重新设计您的课程:

public class SellStatement
{
    List<string> _productName = new List<string>();
    List<double> _quantity = new List<double>();
    List<double> _ratePerQuantity = new List<double>();

    public long billNo {get; set;}
    public DateTime paymentDate  {get; set;}
    public List<string> ProductName { get { return _productName; } }
    public List<double> quantity { get { return _quantity; } }
    public List<double> ratePerQuantity { get { return _ratePerQuantity; } }
}
于 2013-05-02T10:55:54.043 回答