简体   繁体   中英

Getting the value of a tuple using reflection

so I'm trying to get a tuple's value using reflection, the only problem is that I get an exception: System.Reflection.TargetInvocationException. I've tried getting its value as one comment suggested here: Casting to a Tuple<object,object> , var itemX = t.GetProperty("ItemX").GetValue(data); If I uses lem.FieldType.GetProperty("Item1").Name , I can get the name back as Item1, Item2 , etc..., am I using it correctly or is there any other way?

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

And my tuple:

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

Let's query tuple for its Item1..ItemN properties; we can do it with a help of Linq and regular expressions , eg

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

Time to wrap it into your method:

  ...
  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}");
  }
  ...

Edit: let's start from getting all fields which are of type Tuple<,...,> (see comments below):

  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

And now we are ready to use my code above:

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

Tuple is defined like this: Tuple<T1,T2,T3,T4,T5,T6,T7,TRest> .

Following the number of values inside tuple its not the same logic so to read tuple in all case (even with 8 items or more) with reflection just use this piece of code (general coding):

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

You could use:

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM