【发布时间】:2016-05-21 17:12:54
【问题描述】:
我有一个类
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;
}
上述方法返回的e中接收Listproducts的WCF的完成事件:
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;
}
}
我认为我的概念在这里是错误的。创建 List 对象的方法是否正确?
编辑
在页面的构造函数中,这就是我订阅GetObjectCompleted 事件的方式
service.GetObjectCompleted += service_GetObjectCompleted;
在按钮单击事件中,我正在异步调用 GetObject
service.GetObjectAsync();
【问题讨论】:
-
你在什么时候得到这个异常。 ?
-
在
service_GetObjectCompleted中我引用了e,这意味着它的null。尽管从GetObject返回了一个对象,但它为空。我究竟做错了什么?发送创建其他类列表的对象是否正确? -
你能显示你的客户代码吗?如何调用 GetObject 操作?您如何订阅 GetObject Completed Event
-
e只是一个事件参数。我认为它不会返回数据或Listproducts。 -
@Viru 检查已编辑帖子
标签: c# list object nullreferenceexception