gpt4 book ai didi

C# Func<> 和泛型

转载 作者:太空狗 更新时间:2023-10-29 20:29:15 24 4
gpt4 key购买 nike

所以,在处理 Func<>、泛型和 lambda 表达式时,我有点不适应,但我想我已经(有点)了解了总体思路,但仍然有点困惑。

我已经实现了 SortableObservableCollection 类(从网上某处获取 - 感谢我从谁那里得到它!)并且它是这样使用的:

_lookuplistViewModel.Sort(x => x.BrandName, ListSortDirection.Ascending);

其中 x 是由可排序集合实现的对象类型。在这个例子中,BrandName 是实现的对象类型的属性,但我想在泛型类中使用上面的代码并传入要排序的属性。排序方法如下所示:

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 是要排序的属性。理想情况下,这应该是类型安全的,但一个字符串就足够了。

谁能帮我指引正确的方向?

最佳答案

只需让您的构造函数 sig 与 sort 方法的 sig 相匹配,并缓存参数以便在调用 Sort() 时在集合中使用。所以不是“字符串属性”,而是排序方法的任何 sig。

然后传递的参数将是一个函数,它可以是特定类型的并将您定向到元素,实例化将是

_medProd = new ExtendedLookupManagerViewModel<MedicinalProductViewModel, MedicinalProduct>(x => x.BrandName, ListSortDirection.Ascending);

关于C# Func<> 和泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3343597/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com