Object抛出NullReferenceException

时间:2016-02-11 04:13:09

标签: c# list object nullreferenceexception

  • 我的课程Product包含少量公开properties

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

  • 我的service.svn类中有一个方法,我正在检索行,并希望通过创建ListOfProducts对象并将Product对象添加到类ListOfProducts中的List中并返回此对象。 但似乎不是它应该做的方式。因为收到此列表的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;
    }
}

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

修改

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

service.GetObjectCompleted += service_GetObjectCompleted;

在按钮点击事件中,我正在调用GetObject异步

service.GetObjectAsync();

2 个答案:

答案 0 :(得分:0)

反序列化程序did not call your constructor!

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

答案 1 :(得分:0)

<强>解决

问题发生在service_GetObjectCompleted事件中。我需要像list一样引用它,而不是像e.Result那样引用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;
    }
}