[英]C# Func<> and generics
因此,在處理Func <>,Generics和lambda表達式時,我有點不在我的舒適區域,但我認為我得到了一般的想法(有點),但仍然有點困惑。
我已經實現了SortableObservableCollection類(取自某個地方的在線 - 感謝無論是誰從我那里得到它!)它的使用方式如下:
_lookuplistViewModel.Sort(x => x.BrandName, ListSortDirection.Ascending);
其中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;
}
}
}
調用Sort方法的泛型類定義如下:
public class ExtendedLookupManagerViewModel<VMod, Mod> : LookupManagerViewModel
where VMod : ExtendedLookupViewModel
where Mod : ExtendedLookupModelBase
我想像這樣創建一個它的實例:
_medProd = new ExtendedLookupManagerViewModel<MedicinalProductViewModel, MedicinalProduct>(string property);
其中property
是要排序的屬性。 理想情況下,這應該是類型安全的,但字符串就足夠了。
任何人都可以幫助引導我朝着正確的方向前進嗎?
您不應該接受字符串屬性參數,而是接受Func<T, IComparable>
,其中T可能是VMod或Mod,具體取決於您要排序的內容。
只需使構造函數sig與sort方法的sig匹配,並在調用Sort()時緩存params以便在集合中使用。 所以不是“字符串屬性”,而是對於sort方法的sig。
然后傳遞的參數將是一個func,它可以是特定於類型的,並將您引導到元素,實例化將是
_medProd = new ExtendedLookupManagerViewModel<MedicinalProductViewModel, MedicinalProduct>(x => x.BrandName, ListSortDirection.Ascending);
那么,你的Sort方法只在TKey
是通用的--T來自哪里? 我懷疑它應該是Func<VMod, TKey>
或Func<Mod, TKey>
但是我不確定你從哪個中顯示出來。
BrandName
是什么屬性 - MedicinalProductViewModel
或MedicinalProduct
? 假設它是MedicinalProduct
,您的方法應聲明為:
public void Sort<TKey>(Func<Mod, TKey> keySelector, ListSortDirection direction)
那時我懷疑它會起作用......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.