How to add an item of type T to a List<T> without knowing what T is?

人走茶凉 提交于 2019-12-23 07:20:16

问题


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?

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);
  }
  ...

I'd prefer if it were possible to do something like this:

((List<T>) e.CollectionView.SourceCollection).Add((T)e.Item);

Any ideas?


回答1:


Simply don't use generics here:

IList source = (IList)e.CollectionView.SourceCollection;
source.Add(e.Item);

You could also use ICollection in place of IList.




回答2:


Since generic collections implement object-based interfaces defined in the System.Collections namespace, you can do this:

((System.Collections.IList) e.CollectionView.SourceCollection).Add(e.Item);

Of course the type checking is now shifted to runtime, so you need to make sure that e.Item would be of the correct type, because the compiler cannot check it after the cast.




回答3:


You could make a specific typed class?

public class MyClass<ABC>
    {
        private void DataGridCollectionViewSource_CommittingNewItem(
              object sender, DataGridCommittingNewItemEventArgs e)
        {
            Type t = e.CollectionView.SourceCollection.GetType();

        if (t == typeof(List<ABC>))
        {
            List<ABC> source = e.CollectionView.SourceCollection as List<ABC>;
            source.Add(e.Item as ABC);
        }
    }
}

or not depending on the context of what your trying to do....




回答4:


void AddItem<T>(IEnumerable sourceCollection, object item)
{
     ((List<T>)sourceCollectio).Add((T)item); 
}

Then

Type t = e.CollectionView.SourceCollection.GetType(); 
if (t == typeof(List<Person>)) { 
    AddItem<Person>(e.CollectionView.SourceCollection, e.Item);
} else if (t == typeof(List<Place>)) { 
    AddItem<Place>(e.CollectionView.SourceCollection, e.Item);
} 


来源:https://stackoverflow.com/questions/9468087/how-to-add-an-item-of-type-t-to-a-listt-without-knowing-what-t-is

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!