在运行时之前,在不知道类型的情况下转换 e.NewItems
本文关键字:情况下 转换 NewItems 不知道 运行时 类型 | 更新日期: 2023-09-27 18:37:28
所以我有 6 个集合更改的事件处理程序,并意识到我需要摆脱这些重复的代码。它们之间的唯一区别是 Cast 中的类型。
e.NewItems.Cast<MyClass>().ForEach(l => l = //stuff);
由于NewItems是一个IList,我找到了一种在集合中获取类型的方法,我想在Cast中使用它。
var t = sender.GetType().GetGenericArguments().FirstOrDefault().GetType();
问题是我不能在 Cast 的类型括号<>中使用变量。我有什么方法可以做到这一点或做一些完成同样的事情吗?
编辑:
private void Profiles_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
e.NewItems.Cast<Profile>().ForEach(l => PerformOperation(l, DatabaseOperation.Add, false));
e.NewItems.Cast<Profile>().ForEach(l => l.PropertyChanged += OnPropertyChanged);
break;
case NotifyCollectionChangedAction.Move:
break;
case NotifyCollectionChangedAction.Remove:
e.OldItems.Cast<Profile>().ForEach(l => PerformOperation(l, DatabaseOperation.Remove, false));
e.OldItems.Cast<Profile>().ForEach(l => l.PropertyChanged -= OnPropertyChanged);
break;
case NotifyCollectionChangedAction.Replace:
break;
case NotifyCollectionChangedAction.Reset:
break;
default:
throw new ArgumentOutOfRangeException();
}
}
泛型函数怎么样?
public void YourMethod (IList<T> yourList)
{
yourList.ForEach(l => l = //stuff);
}
我不完全清楚你想做什么,但听起来你可以写一个接口或基类。这样你就可以做到:
e.NewItems.Cast<IMyClass>().ForEach(l => l //stuff);
或
e.NewItems.Cast<MyBaseClass>().ForEach(l => l //stuff);