[英]Object of type 'System.Int16' cannot be converted to type 'System.Nullable`1[System.Int32]
[英]Object of type 'System.Reflection.ParameterInfo' cannot be converted to type 'System.Int32'
我正在嘗試為對象編寫擴展方法,該方法會將對象的結構轉儲到調試輸出。 在索引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();
}
}
轉儲索引器屬性是個壞主意。 它類似於“轉儲方法”。 這是不可能的。
在嘗試獲取值之前,還應考慮使用PropertyInfo.CanRead。
您本質上是在嘗試訪問SomeProp [foo,bar ...] ...因此; 什么是明智的指數值? 對於整數,也許0,0,0 ...是安全的-也許不是。 這取決於上下文。 就我個人而言,我不確定這是否是最好的方法。 我可能會查看主要對象上的IList
,但IList
-只是查看常規屬性...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.