【发布时间】:2019-12-27 08:52:12
【问题描述】:
所以我试图使用反射来获取元组的值,唯一的问题是我得到了一个异常: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);
【问题讨论】:
-
你能发一个minimal reproducible example 以便更清楚到底是什么问题吗?另外,TargetInvocationException 包含一个更重要的 InnerException,您能检查一下并告诉我们它说什么吗?
-
tuple .GetType() .GetProperties() .Where(prop => Regex.IsMatch(prop.Name, "Item[0-9]+")) .ToDictionary(prop => prop.Name, prop => prop.GetValue(tuple));获取所有Item1..ItemN属性名称和值 -
小心
.ToString()- 如果GetValue(this,null)返回null怎么办?
标签: c# reflection tuples