0

I need to implement Comparison delegate for Tuple. And I have a column number by which I want to compare Tuples.

For now I got to:

int sortedColumn;
Comparison<Tuple<T1, T2, T3>> tupleComparison = (x, y) =>
{
    // I want to access x.Item2 if sortedColumn = 2
        // x.Item3 if sortedColumn = 2 etc      
};

How can I do this in c#?

Can I do it without using switch?

4

2 回答 2

3

一个可能不为人知的事实是所有元组都实现了有点晦涩的接口ITuple。该接口定义了两个方法(Length返回元组中的项目数和一个索引访问方法,[]从零开始),但它们都是隐藏的,这意味着您必须将元组变量显式转换为实现的接口,然后使用相关方法。

请注意,您必须最终将访问的项目转换为其固有类型,因为索引访问方法总是返回一个object.

Comparison<Tuple<T1, T2, T3>> tupleComparison = (x, y) =>
{
    var columnValue = (int)((ITuple)x)[sortedColumn];     // Don't forget to cast to relevant type
};
于 2018-06-25T19:51:24.740 回答
2

我可能会选择if/elseswitch,但如果你想避免这种情况(例如,你可以将它与 any 一起使用Tuple),你可以使用反射:

Comparison<Tuple<T1, T2, T3>> tupleComparison = (x, y) =>
{
    var prop = typeof(Tuple<T1, T2, T3>).GetProperty("Item" + sortedColumn);
    var xItem = prop.GetValue(x);
    var yItem = prop.GetValue(y);
    return // something to compare xItem and yItem
};
于 2013-09-01T12:31:46.010 回答