结构体
struct BLC
{
int a;
int b;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
int[] cc;
}
遍历
Type type = typeof(BLC);
foreach (FieldInfo mi in type.GetFields(BindingFlags.Public | BindingFlags.Instance))
{
stest += mi.Name. + "." + mi.GetValue(blc);
}前面的a,b都Ok,可到了cc里,name =System.int[] 没有value。
请高手指教
struct BLC
{
int a;
int b;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
int[] cc;
}
遍历
Type type = typeof(BLC);
foreach (FieldInfo mi in type.GetFields(BindingFlags.Public | BindingFlags.Instance))
{
stest += mi.Name. + "." + mi.GetValue(blc);
}前面的a,b都Ok,可到了cc里,name =System.int[] 没有value。
请高手指教
将数组连接到字符串后面,会调用数组的tostring方法,返回“System.int[]”好比:Console.WriteLine(new int[] { 1, 2, 3 });你觉得输出123,其实输出还是“System.int[]”。
if (mi.GetValue(blc).GetType() == typeof(int[]))
stest += mi.Name. + "." + string.Join(", ", (mi.GetValue(blc) as int[]));
else
stest += mi.Name. + "." + mi.GetValue(blc);
谢谢哈但如果这里的cc[]不一定是Int[]型呢?有没有个通用的方法。
我之前有看到 if(mi.GetType().IsArray)
{
object[] users = (object)mi as object[];
for (int i = 0; i <users.Length; i++)
{
stest += mi.Name + "." + users[i].ToString();
}
}
else
stest += mi.Name. + "." + mi.GetValue(blc);去判断是不是数组,但好像不太对。不知道您有没有啥高招呢?
using System.Collections;namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
object o = new int[] { 1, 2, 3 };
if (o is Array)
{
Console.WriteLine(o.GetType().GetElementType());
foreach (object item in (o as IEnumerable))
{
Console.WriteLine(item);
}
}
}
}
}System.Int32
1
2
3
Press any key to continue . . .
我的意思是我上面的code中 if(mi.GetType().IsArray)这个就不会是true.
mi.GetValue(blc) is Array别的看我的代码。
Type type = typeof(BLC);
foreach (FieldInfo mi in type.GetFields(BindingFlags.Public | BindingFlags.Instance))
{ if(mi.GetValue(blc) is Array)
{
foreach(object item in (mi.GetValue(blc) as IEnumerable))
{
stest += mi.Name + "." + item.ToString();
}
}
else
stest += mi.Name + "." + mi.GetValue(blc);
}
不知道对于数据结构里还有结构体的怎么办呢?
那需要递归获取。能帮忙show一下sample code吗?网上查了下,还没找到。
谢谢呀。如果需要另外开个贴也行的。非常感谢你。