Skip to main content
 首页 » 编程设计

c#之PropertyInfo.GetValue(object) 因 IEnumerableT> [C#, Reflection] 而失败

2024年02月06日12kenshinobiy

我有以下问题:
我目前正在编写相当于 PHP 的 var_dump 的 c# -方法。它与“简单”类和结构(甚至数组)完美配合。
我唯一的问题是涉及到其他 IEnumerable<T> , 比如 List<T>等:

调试器抛出 TargetParameterCountException .我的代码如下所示:

Type t = obj.GetType(); // 'obj' is my variable, i want to 'dump' 
string s = ""; 
PropertyInfo[] properties = t.GetProperties(); 
 
for (int i = 0; i < properties.Length; i++) 
{ 
    PropertyInfo property = properties[i]; 
 
    object value = property.GetValue(obj); // <-- throws exception 
 
    if (value is ICollection) 
    { 
        // Code for array parsing - is irrelevant for this problem 
    } 
    else 
        s += "Element at " + i + ": " + value.GetType().FullName + " " + value.ToString() + "\n"; 
} 
 
return s; 

我知道,我可以用 PropertyInfo.GetIndexParameters() 以某种方式获取索引,但我没有想出如何正确使用它。

编辑:我还想指出,我在编译时既不知道 IEnumerable 的大小,也不知道 Type T。

请您参考如下方法:

不确定这是否是您的问题,但根据 MSDN :

You call the GetValue(Object) overload to retrieve the value of a non-indexed property; if you try to retrieve the value of an indexed property, the method throws a TargetParameterCountException exception.

来自同一页面上的示例:

     if (prop.GetIndexParameters().Length == 0) 
        Console.WriteLine("   {0} ({1}): {2}", prop.Name, 
                          prop.PropertyType.Name, 
                          prop.GetValue(obj)); 
     else 
        Console.WriteLine("   {0} ({1}): <Indexed>", prop.Name, 
                          prop.PropertyType.Name);