How to get Tuple property by property index in c#?

拥有回忆 提交于 2019-12-13 04:31:06

问题


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?


回答1:


I'd probably go with if/else or switch, but if you want to avoid that (e.g. so you can use it with any Tuple), you can use reflection:

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
};



回答2:


A perhaps little known fact is that all tuples implement the slightly obscure interface ITuple. This interface defines two methods (Length returning the number of items in the tuple, and an index access method, [] - which is zero-based), but both of them are hidden, meaning that you have to explicitly cast your tuple variable to the implemented interface, and then use the relevant method.

Note that you have to cast the accessed item finally to its innate type, as the index access method always returns an object.

Comparison<Tuple<T1, T2, T3>> tupleComparison = (x, y) =>
{
    var columnValue = (int)((ITuple)x)[sortedColumn];     // Don't forget to cast to relevant type
};


来源:https://stackoverflow.com/questions/18558353/how-to-get-tuple-property-by-property-index-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!