使用反射获取元组的值

时间:2019-12-27 08:52:12

标签: c# reflection tuples

所以我试图使用反射来获取元组的值,唯一的问题是我得到了一个异常:System.Reflection.TargetInvocationException。我尝试获得其价值,因为这里提出了一条建议: Casting to a Tuple<object,object>var itemX = t.GetProperty("ItemX").GetValue(data);如果我使用lem.FieldType.GetProperty(“ Item1”)。Name,我可以将名称取回为Item1,Item2等,是我正确使用还是还有其他方法吗?

FieldInfo[] fields = this.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);
FieldInfo[] tuples = fields.Where(field=>typeof(IStructuralEquatable).IsAssignableFrom(field.FieldType) && typeof(IStructuralComparable).IsAssignableFrom(field.FieldType)).ToArray();

Debug.WriteLine(tuples.Length.ToString()" ->");
foreach (var elem in tuples)
{
    Debug.WriteLine(elem.FieldType.GetProperty("Item1").GetValue(this,null).ToString());

    PropertyInfo[] info = elem.FieldType.GetProperties();
    Debug.WriteLine(info[0].GetValue(this,null).ToString());
    for(int i=0;i<info.Length;i++)
    {
        Debug.WriteLine(info[i].GetValue(this,null).ToString());
    }

我的元组:

protected Tuple<string,int, int, int> testTuple = new Tuple<string, int, int, int>("Test",1,0,1);

2 个答案:

答案 0 :(得分:2)

让我们的{em>查询 tuple的{​​{1}}属性;我们可以借助 Linq 正则表达式,例如

Item1..ItemN

是时候将其包装到您的方法中了:

  using System.Linq;
  using System.Reflection;
  using System.Text.RegularExpressions;

  ...

  Dictionary<string, object> result = testTuple
    .GetType()
    .GetProperties()
    .Where(prop => prop.CanRead)
    .Where(prop => !prop.GetIndexParameters().Any())
    .Where(prop => Regex.IsMatch(prop.Name, "^Item[0-9]+$"))
    .ToDictionary(prop => prop.Name, prop => prop.GetValue(testTuple));

编辑:让我们首先获取所有 ... foreach (var tuple in tuples) { var result = tuple .GetType() .GetProperties() .Where(prop => prop.CanRead) .Where(prop => !prop.GetIndexParameters().Any()) .Where(prop => Regex.IsMatch(prop.Name, "^Item[0-9]+$")) .Select(prop => new { name = prop.Name, value = prop.GetValue(tuple), }); foreach (var item in result) Debug.WriteLine($"{item.name} = {item.value}"); } ... 类型的字段(请参见下面的评论):

Tuple<,...,>

现在我们可以使用上面的代码了:

  Object objectToInspect = this;

  HashSet<Type> typleTypes = new HashSet<Type>() {
    typeof(Tuple<>),
    typeof(Tuple<,>),
    typeof(Tuple<,,>),
    typeof(Tuple<,,,>),
    typeof(Tuple<,,,,>),
    typeof(Tuple<,,,,,>),
    typeof(Tuple<,,,,,,>),
    typeof(Tuple<,,,,,,,>),
  };

  var fieldsWithTuples = objectToInspect
    .GetType()
    .GetFields(BindingFlags.NonPublic |
               BindingFlags.Instance |
               BindingFlags.Public |
               BindingFlags.Static |
               BindingFlags.FlattenHierarchy)
    .Where(field => field.FieldType.IsGenericType)
    .Where(field => typleTypes.Contains(field.FieldType.GetGenericTypeDefinition()))
    .Select(field => new {
      name  = field.Name,
      value = field.GetValue(field.IsStatic
                 ? null                     // we should provide null for static
                 : objectToInspect)
    })
    .Where(item => item.value != null);
 // .Select(item => item.value) // if you want tuple values
 // .ToArray();                 // materialized as an array

答案 1 :(得分:0)

元组的定义如下:Tuple<T1,T2,T3,T4,T5,T6,T7,TRest>

在元组中跟随值的数量逻辑不同 因此,要在所有情况下(即使有8项或更多)读取元组,只需使用以下代码(通用编码)即可:

    public IEnumerable<object> EnumerateValueTuple(object valueTuple)
    {
        var tuples = new Queue<object>();
        tuples.Enqueue(valueTuple);

        while (tuples.Count > 0 && tuples.Dequeue() is object tuple)
        {
            foreach (var field in tuple.GetType().GetFields())
            {
                if (field.Name == "Rest")
                    tuples.Enqueue(field.GetValue(tuple));
                else
                    yield return field.GetValue(tuple);
            }
        }
    }

您可以使用:

var item = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);

foreach(var value in EnumerateValueTuple(item))
  Console.Out.WriteLine(value); // Prints "1 2 3 4 5 6 7 8 9 10 11"
相关问题