[英]Object throws NullReferenceException
我有一個包含很少公共properties
的類Product
我還有另一個類ListOfProducts
,應該包含一個Product
對象列表
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.