我正在处理一个事件,该事件传递指向一个列表和一个 T 新项目的事件参数,我的工作是将新项目添加到列表中。
如果不检查我知道 T 可能是的所有类型,我该如何做到这一点?
当前的代码是这样的几十行:
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);
}
...
如果可以的话,我更愿意这样做:
((List<T>) e.CollectionView.SourceCollection).Add((T)e.Item);
有什么想法吗?
最佳答案
在这里不要使用泛型:
IList source = (IList)e.CollectionView.SourceCollection;
source.Add(e.Item);
您也可以使用 ICollection
代替 IList
。
关于c# - 如何在不知道 T 是什么的情况下将 T 类型的项目添加到 List<T>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9468087/