[英]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.