如何通过 c# 中的属性索引获取元组属性? [英] How to get Tuple property by property index in c#?

查看:34
本文介绍了如何通过 c# 中的属性索引获取元组属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为元组实现 Comparison 委托.我有一个列号,我想通过它来比较元组.

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

现在我必须:

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

我怎样才能在 C# 中做到这一点?

How can I do this in c#?

我可以不使用switch来实现吗?

Can I do it without using switch?

推荐答案

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

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

这篇关于如何通过 c# 中的属性索引获取元组属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆