我正在尝试编写一个反射类(用于自定义序列化)。 我对遍历数组的语法感到困惑。 以下适用于非数组,但我遗漏了数组部分,无法从此处的其他答案(其中一些无法编译)中找出答案...
要实现反序列化,必须获取目标类中每个对象的可写引用,以便从先前序列化的数据中设置它们的值。
提前感谢您的任何提示!
private static void diagPrint(Object val)
{
if (val == null)
return; // whoops
Type t = val.GetType();
string r = "";
if (t.IsArray)
{
Type t_item = t.GetElementType();
r += "Type=" + t_item.Name + "[], value=[";
//
// ??? OK, now what ? How to iterate through the elements of the array ???
// Needs to work for arrays of simple type like Bool or arrays of objects...
//
r += "]";
}
else
{
r += "Type=" + t.Name + ", value=";
r += val.ToString();
}
MessageBox.Show(r);
}
最佳答案
最简单的方法是将对象转换为数组实现的IEnumerable
。
IEnumerable items = val as IEnumerable;
foreach (object o in items)
{
r += ((o != null) ? o.ToString() : "") + ", ";
}
关于C# 反射 : getting the values of an array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19350666/