委托创建者为可空类型创建比较器
Delegate creator to create comparitor for nullable types
我正在使用自定义 ListView
控件,该控件无法使用其内部比较方法处理空值。我的梦想是比较只是工作,没有太多配置。
大多数列的值都可以为 nullable decimal 类型,但有些列有其他类型,例如可以为 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
假设您希望您的方法 return 一个 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);
我正在使用自定义 ListView
控件,该控件无法使用其内部比较方法处理空值。我的梦想是比较只是工作,没有太多配置。
大多数列的值都可以为 nullable decimal 类型,但有些列有其他类型,例如可以为 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
假设您希望您的方法 return 一个 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);