对象抛出 NullReferenceException

本文关键字:NullReferenceException 对象 | 更新日期: 2023-09-27 18:34:05

  • 我有一个包含很少公共properties的类Product

  • 我有另一个类ListOfProducts,它应该包含一个Product对象列表

  • 我的 service.svn 类中有一个方法,我正在检索行,并希望通过创建 ListOfProducts 的对象Product将对象添加到类 ListOfProducts 中存在的列表中并返回此对象。但似乎这不是应该做的方式。因为接收此列表的service_GetObjectCompleted抛出NullReferenceException .

ListOfProducts

[DataContract()]
public class ListOfProducts
{
    [DataMember()]
    public List<Product> ProductList { get; set; }
    public ListOfProducts()
    {
        ProductList = new List<Product>();
    }
}

Service.svn 类中用于创建对象ListOfProducts并将Product对象添加到其列表

的方法
public ListOfProducts GetObject()
{
    ListOfProducts Listproducts = new ListOfProducts();
    ........
    using (IDataReader reader = cmd.ExecuteReader())
    {
        while (reader.Read())
        {
            Product product = new Product(reader["Name"].ToString(), reader["Code"].ToString());
            Listproducts.ProductList.Add(product);
        }
    }
    return Listproducts;
}

WCF 的已完成事件,该事件接收从上述方法返回的Listproducts e

void service_GetObjectCompleted(object sender, GetObjectCompletedEventArgs e)
{
    if (e.Result.Count != 0)  //throws NullReferenceException
    {
        PagedCollectionView pagingCollection = new PagedCollectionView(e.Result);
        pgrProductGrids.Source = pagingCollection;
        grdProductGrid.ItemsSource = pagingCollection;
    }
}

我认为我的概念在这里是错误的。这是创建列表对象的正确方法吗?

编辑

在页面的构造函数中,这就是我订阅GetObjectCompleted事件的方式

service.GetObjectCompleted += service_GetObjectCompleted;

在我异步调用GetObject按钮单击事件上

service.GetObjectAsync();

对象抛出 NullReferenceException

反序列化程序没有调用你的构造函数!

因此,当您在服务的另一端检索ListOfProducts时,ProductList属性仍null

已解决

问题出在service_GetObjectCompleted事件中。我不是像e.Result那样引用list,而是需要像e.Result.ProductList一样引用它。所以这是有效的版本:

void service_GetObjectCompleted(object sender, GetObjectCompletedEventArgs e)
{
    if (e.Result.Productlist.Count != 0)  
    {
        PagedCollectionView pagingCollection = new PagedCollectionView(e.Result.Productlist);
        pgrProductGrids.Source = pagingCollection;
        grdProductGrid.ItemsSource = pagingCollection;
    }
}