簡體   English   中英

對象拋出NullReferenceException

[英]Object throws NullReferenceException

  • 我有一個包含很少公共properties的類Product

  • 我還有另一個類ListOfProducts ,應該包含一個Product對象列表

  • 我的service.svn類中有一個方法,我在其中檢索行,並想通過創建ListOfProducts對象並返回此對象,將Product對象添加到存在於ListOfProducts類中的List中。 但是似乎它不是應該完成的方式。 因為接收到此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對象添加到其List中

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的Completed事件,該事件從上述方法返回的e中接收Listproducts

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

反序列化器未調用您的構造函數!

因此,當您在服務的另一端檢索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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM