如何将数据源转换为List< T&gt ;? [英] How to Casting DataSource to List<T>?

查看:105
本文介绍了如何将数据源转换为List< T&gt ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下方法可以在DataGridView上加载产品

I have the following method that load products on a DataGridView

private void LoadProducts(List<Product> products)
{
    Source.DataSource = products;  // Source is BindingSource
    ProductsDataGrid.DataSource = Source;
}

现在,我正试着给我回去保存它们,如下所示

And now I'm trying to give me back to save them as shows below.

private void SaveAll()
{
   Repository repository = Repository.Instance;
   List<object> products = (List<object>)Source.DataSource; 
   Console.WriteLine("Este es el número {0}", products.Count);
   repository.SaveAll<Product>(products);
   notificacionLbl.Visible = false;
}

但是我收到了 InvalidCastException 在此行上:

But I get an InvalidCastException on this line:

List<object> products = (List<object>)Source.DataSource;

那么如何将数据源转换为列表?

So how can I cast the DataSource to an List?

推荐答案

您不能将协变直接转换为List;

You can't cast covariantly directly to List;

其中之一:

List<Product> products = (List<Product>)Source.DataSource;

或:

List<Object> products = ((List<Product>)Source.DataSource).Cast<object>().ToList();

这篇关于如何将数据源转换为List&lt; T&gt ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆