PropertyInfo.GetValue(对象)失败,返回IEnumerable<;T>;[C#,反思]
我有以下问题:PropertyInfo.GetValue(对象)失败,返回IEnumerable<;T>;[C#,反思],c#,reflection,ienumerable,var-dump,propertyinfo,C#,Reflection,Ienumerable,Var Dump,Propertyinfo,我有以下问题: 我目前正在编写PHP的var\u dump-方法的c#等价物。它与“简单”类和结构(甚至与数组)完美结合。 我唯一的问题是涉及到其他IEnumerable,如List等: 调试器正在抛出一个TargetParameterCountException。我的代码如下所示: Type t = obj.GetType(); // 'obj' is my variable, i want to 'dump' string s = ""; PropertyInfo[] properties
我目前正在编写PHP的
var\u dump
-方法的c#等价物。它与“简单”类和结构(甚至与数组)完美结合。我唯一的问题是涉及到其他
IEnumerable
,如List
等:
调试器正在抛出一个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;
Type t=obj.GetType();/'obj'是我的变量,我想'dump'
字符串s=“”;
PropertyInfo[]properties=t.GetProperties();
for(int i=0;i 对象值=property.GetValue(obj);//这与实现IEnumerable
的类型无关。而是关于具有索引器的类型。索引器被视为属性,但它们是特殊属性,需要在获取其值时提供索引参数。如果不这样做,则会出现错误,正如您在这里看到的那样
您可以使用GetIndexParameters()
并检查返回数组的计数,以确定该属性是否为索引器。这将允许您跳过该属性(我假设您在这里会这样做),或使用它来获取其值。这与实现IEnumerable
的类型无关。相反,这与具有索引器的类型有关。索引器被视为属性,但它们是特殊属性,需要在获取其值时为其提供索引参数。如果不这样做,则会出现您在此处看到的错误
您可以使用GetIndexParameters()
并检查返回数组的计数,以确定该属性是否为索引器。这将允许您跳过该属性(我假设您在这里要做的就是这样),或使用它获取其值。不确定这是否是您的问题,但根据:
调用GetValue(Object)重载来检索非索引属性的值;如果尝试检索索引属性的值,该方法将抛出TargetParameterCountException异常
根据同一页上的示例:
if(prop.GetIndexParameters().Length==0)
Console.WriteLine(“{0}({1}):{2}”,prop.Name,
prop.PropertyType.Name,
道具GetValue(obj));
其他的
Console.WriteLine(“{0}({1}):”,prop.Name,
prop.PropertyType.Name);
不确定这是否是您的问题,但根据:
调用GetValue(Object)重载来检索非索引属性的值;如果尝试检索索引属性的值,该方法将抛出TargetParameterCountException异常
根据同一页上的示例:
if(prop.GetIndexParameters().Length==0)
Console.WriteLine(“{0}({1}):{2}”,prop.Name,
prop.PropertyType.Name,
道具GetValue(obj));
其他的
Console.WriteLine(“{0}({1}):”,prop.Name,
prop.PropertyType.Name);
使用PropertyInfo
的GetIndexParameters()
方法来确定属性是否被索引,如果是,则跳过它,或者返回绘图板,看看如何生成它所需的索引,以便在不失败的情况下返回有意义的值。使用GetIndexParameters()
PropertyInfo的方法,以确定属性是否已编制索引,如果已编制索引,则跳过该属性,或返回绘图板,查看如何生成索引它需要返回一个有意义的值而不会失败。如果希望引用IEnumerable,而不仅仅是IEnumerable的项,则可以使用以下方法获取它:
if (propertyInfo.GetMethod.IsPublic)
{
var value = propertyInfo.GetMethod.Invoke(Instance, null);
}
如果您希望引用IEnumerable,而不仅仅是它的项,您可以使用以下方法获得它:
if (propertyInfo.GetMethod.IsPublic)
{
var value = propertyInfo.GetMethod.Invoke(Instance, null);
}
尝试使用此重载:property.GetValue(obj,null)
尝试使用此重载:property.GetValue(obj,null)