如何T类型的项目添加到列表&LT; T&GT;不知道T是什么? [英] How to add an item of type T to a List<T> without knowing what T is?
本文介绍了如何T类型的项目添加到列表&LT; T&GT;不知道T是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我处理这传递事件参数指向一个列表和T的newitem一个事件,而我的工作就是给的newitem添加到列表中。
I'm handling an event which passes event args pointing to a List and a T newitem, and my job is to add the newitem to the List.
我怎么能做到这一点,不检查就我所知牛逼可能是什么?
How can I do this without checking for all the types I know T might be?
目前的code是这几打几行:
The current code is a couple dozen lines of this:
private void DataGridCollectionViewSource_CommittingNewItem(object sender, DataGridCommittingNewItemEventArgs e)
{
Type t = e.CollectionView.SourceCollection.GetType();
if (t == typeof(List<Person>))
{
List<Person> source = e.CollectionView.SourceCollection as List<Person>;
source.Add(e.Item as Person);
}
else if (t == typeof(List<Place>))
{
List<Place> source = e.CollectionView.SourceCollection as List<Place>;
source.Add(e.Item as Place);
}
...
我preFER如果有可能做这样的事情:
I'd prefer if it were possible to do something like this:
((List<T>) e.CollectionView.SourceCollection).Add((T)e.Item);
任何想法?
推荐答案
只要不使用泛型这里:
IList source = (IList)e.CollectionView.SourceCollection;
source.Add(e.Item);
您也可以使用的ICollection
代替的IList
。
这篇关于如何T类型的项目添加到列表&LT; T&GT;不知道T是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文