我正在嘗試編寫將對象的結構轉儲到調試輸出的對象的擴展方法。當propertyInfo被索引時(GetIndexParameters()。Length> 0),我遇到了一個問題。類型'System.Reflection.ParameterInfo'的對象無法轉換爲類型'System.Int32'
我使用以下嘗試:
object value = propInfo.GetValue(myObject, propInfo.GetIndexParameteres());
這導致以下運行時錯誤:
- 類型的對象「System.Reflection.ParameterInfo」不能轉換爲類型「系統.Int32'
任何人有任何想法?該方法的完整代碼如下:
[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();
}
}
阻力最小的路徑我感覺,謝謝! – mnield 2009-05-20 11:53:55