委托创建者为可空类型

时间:2018-01-15 17:34:13

标签: c# delegates nullable

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

大多数列都具有可为空的十进制类型的值,但有些列具有其他类型,如可空整数或非可空类型。

目前我必须写下每一个专栏:

_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

1 个答案:

答案 0 :(得分:1)

假设您希望方法返回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);