使用反射获取元组的值 - c#

所以我试图使用反射来获取元组的值,唯一的问题是我得到了一个异常: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);

参考方案

让我们查询tupleItem1..ItemN属性;我们可以借助Linq和正则表达式(例如

  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

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

  foreach (var tuple in fieldsWithTuples.Select(f => f.value)) {
    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}");
  }

Python 3运算符>>打印到文件 - python

我有以下Python代码编写项目的依赖文件。它可以在Python 2.x上正常工作,但是在使用Python 3进行测试时会报告错误。depend = None if not nmake: depend = open(".depend", "a") dependmak = open(".depend.mak&#…

与哪些运算符>>兼容 - java

我这里没有什么代码int b=3; b=b >> 1; System.out.println(b); 它可以完美工作,但是当我将变量b更改为byte,short,float,double时,它包含错误,但是对于变量int和long来说,它可以完美工作,为什么它不能与其他变量一起工作? 参考方案 位移位运算符(例如>>)与任何整数类型兼…

无法解析Json响应 - php

我正在尝试解析一个包含产品类别的JSON文件,然后解析这些类别中的产品,并在div中显示它们。我的问题:虽然我可以获取类别,但我不知道如何索取产品(并将它们显示在类别下)。我的剧本:<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script> …

在xpath中选择多个条件 - php

我正在尝试使用来自高尔夫比赛的xml提要,以显示每个高尔夫球手在高尔夫球场上的位置。目前,我想展示符合两个条件的所有高尔夫球手(排在前25名,以及所有加拿大高尔夫球手)。这是xml提要的示例。<GolfDataFeed Type="Leaderboards" Timestamp="3/21/2012 9:18:09 PM&…

>> Python中的运算符 - python

>>运算符做什么?例如,以下操作10 >> 1 = 5有什么作用? 参考方案 它是右移运算符,将所有位“右移”一次。二进制10是1010移到右边变成0101这是5