铸造数据源列出< T> [英] Casting DataSource to List<T>
本文介绍了铸造数据源列出< T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下方法加载产品上一个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的
在这条线:
List<object> products = (List<object>)Source.DataSource;
所以,我怎么能投的数据源到一个列表?
So how can I cast the DataSource to an 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();
这篇关于铸造数据源列出< T>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文