如何T类型的项目添加到列表< T>不知道T是什么?类型、项目、列表、GT

由网友(空城一人)分享简介:我处理这传递事件参数指向一个列表和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 th...

我处理这传递事件参数指向一个列表和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

阅读全文

相关推荐

最新文章