委托创建者为可为 null 的类型创建比较器



我正在使用一个自定义ListView控件,该控件无法通过其内部比较方法处理空值。我的梦想是比较只是工作,没有太多配置。

大多数列具有可为 null

的十进制类型的值,但有些列具有其他类型,如可为 null 的整数或不可为空的类型。

目前对于我必须写的每个列:

_priceColumn.Comparitor = delegate (object x, object y)
{
    Ticker xTicker = (Ticker)x;
    Ticker yTicker = (Ticker)y;
    return Nullable.Compare<Decimal>(xTicker.Price, yTicker.Price);
};

我希望能够写出这样的东西:

_priceColumn.Comparitor = ColumnHelpers.CreateNullableComparitor(Ticker.Price) //It would have to look up the type of Ticker.Price itself and call the correct Nullable.Compare.

_priceColumn.Comparitor = ColumnHelpers.CreateNullableComparitor(Ticker.Price, Decimal?) //I pass  Decimal? to it, which is the type of Ticker.Price

我不知道如何让它创建与所需代表的签名匹配的东西。

用一些通用的魔法或通过检查类型并选择正确的方法可能很容易解决。

我正在使用的自定义ListView是这个:https://www.codeproject.com/Articles/20052/Outlook-Style-Grouped-List-Control

假设您希望方法返回Comparison<object> .你可以编写这样的方法:

public static Comparison<object> CreateNullableComparitor<T>(Func<Ticker, T?> keySelector) where T: struct {
    return (o1, o2) => Comparer<T>.Default.Compare(keySelector((Ticker)o1), keySelector((Ticker)o2));
}

并像这样使用它:

CreateNullableComparitor(x => x.Price);

如果值的类型不可为空,则类型推断在此处不起作用,因此您必须执行以下操作:

CreateNullableComparitor<decimal>(x => x.NonNullablePrice);

最新更新