因此,在处理Func <>,Generics和lambda表达式时,我有点不在我的舒适区域,但我认为我得到了一般的想法(有点),但仍然有点困惑.
我已经实现了SortableObservableCollection类(取自某个地方的在线 - 感谢无论是谁从我那里得到它!)它的使用方式如下:
_lookuplistViewModel.Sort(x => x.BrandName, ListSortDirection.Ascending);
Run Code Online (Sandbox Code Playgroud)
其中x是可排序集合实现的对象类型.在这个例子中,BrandName是实现的对象类型的属性,但是我想在泛型类中使用上面的代码并传入要排序的属性.Sort方法如下所示:
public void Sort<TKey>(Func<T, TKey> keySelector, ListSortDirection direction)
{
switch (direction)
{
case ListSortDirection.Ascending:
{
ApplySort(Items.OrderBy(keySelector));
break;
}
case System.ComponentModel.ListSortDirection.Descending:
{
ApplySort(Items.OrderByDescending(keySelector));
break;
}
}
}
Run Code Online (Sandbox Code Playgroud)
调用Sort方法的泛型类定义如下:
public class ExtendedLookupManagerViewModel<VMod, Mod> : LookupManagerViewModel
where VMod : ExtendedLookupViewModel
where Mod : ExtendedLookupModelBase
Run Code Online (Sandbox Code Playgroud)
我想像这样创建一个它的实例:
_medProd = new ExtendedLookupManagerViewModel<MedicinalProductViewModel, MedicinalProduct>(string property);
Run Code Online (Sandbox Code Playgroud)
在哪里property排序的属性.理想情况下,这应该是类型安全的,但字符串就足够了.
任何人都可以帮助引导我朝着正确的方向前进吗?
只需使构造函数 sig 与排序方法的 sig 匹配,并缓存参数以便在调用 Sort() 时在集合中使用。所以不是“字符串属性”,而是排序方法的任何 sig。
然后传递的参数将是一个可以是特定类型的函数并引导您到该元素,实例化将是
_medProd = new ExtendedLookupManagerViewModel<MedicinalProductViewModel, MedicinalProduct>(x => x.BrandName, ListSortDirection.Ascending);
Run Code Online (Sandbox Code Playgroud)