我正在尝试为对象编写扩展方法,将对象的结构转储到调试输出。当propertyInfo被索引时,我遇到了问题(GetIndexParameters()。Length> 0)。
我尝试过使用以下内容:
object value = propInfo.GetValue(myObject, propInfo.GetIndexParameteres());
这会导致以下运行时错误:
有人有任何想法吗?该方法的完整代码如下:
[System.Diagnostics.Conditional("DEBUG")]
public static void DebugObject(this object debugObject)
{
System.Diagnostics.Debug.WriteLine("Debugging object: " + debugObject.GetType().Namespace);
System.Diagnostics.Debug.WriteLine(String.Format("> {0}", debugObject.GetType()));
System.Diagnostics.Debug.Indent();
try
{
if (debugObject.GetType().IsArray)
{
object[] array = ((object[])debugObject);
for (int index = 0; index < array.Length; index++)
{
System.Diagnostics.Debug.WriteLine(String.Format("- {{0}} = [{1}]", index, array[index]));
}
return;
}
object value = null;
foreach (System.Reflection.PropertyInfo propInfo in debugObject.GetType().GetProperties())
{
try
{
if (propInfo.IsIndexed())
{
System.Diagnostics.Debug.WriteLine(propInfo.ReflectedType.IsArray + " is indexed");
// THIS IS WHERE IT CHOKES. As an example, try sending in something of type System.Net.Mail.MailMessage;
value = propInfo.GetValue(debugObject, propInfo.GetIndexParameters());
}
else
{
value = propInfo.GetValue(debugObject, null);
}
if (value != null)
{
System.Diagnostics.Debug.WriteLine(String.Format("> {0} = [{1}]", propInfo.Name, value));
if (
(value.GetType() != typeof(string))
&&
(value.GetType() != typeof(int))
)
{
value.DebugObject();
}
}
}
catch (System.Reflection.TargetParameterCountException tpce)
{
System.Diagnostics.Debug.WriteLine(
String.Format(
"> Could not run GetValue for {1} (type '{0}', '{2}') because of incorrect prarmeters",
propInfo.GetType().ToString(),
propInfo.Name,
propInfo.PropertyType.Namespace
)
);
}
}
}
finally
{
System.Diagnostics.Debug.Unindent();
}
}
答案 0 :(得分:1)
转储索引器属性是个坏主意。它类似于“转储方法”。这是不可能的。
在尝试获取值之前,还要考虑使用PropertyInfo.CanRead。
答案 1 :(得分:0)
你基本上是试图访问SomeProp [foo,bar ...] ......所以;什么是合理的指数值?对于整数,也许0,0,0 ......是安全的 - 也许不是。这取决于具体情况。就个人而言,我不确定这是最好的方式;我可能会在主要对象上查看IList
,但除此之外 - 只需查看常规属性......