打印结构体中的成员名和值
如果存在嵌套结构体,则递归进入
如果存在结构体数组,也递归进入,记录下标
此过程是动态的,改变结构体的成员及嵌套层数无需修改本段代码
嵌套结构体的本质可以看作一颗树,此函数可以得出结构体之间的嵌套关系
string[] Father = new string[100];
int i = 0;
public List<string> MyTree = new List<string>();
StreamWriter sw = new StreamWriter("SaveData.txt");
public void GetGNSSMessage(object temp, string ctag)//此处获取所有信息,显示
{
if (temp == null)
return;
else
{
Type t = temp.GetType();
System.Reflection.FieldInfo[] fields = t.GetFields();//获取结构体所有成员名
foreach (System.Reflection.FieldInfo field in fields)
{
if (field.GetValue(temp) is Enum)//枚举类型
{
}
else if (field.GetValue(temp) != null && field.GetValue(temp).GetType().IsPrimitive)//是否为基础类型
{
}
else//自定义结构类型
{
Father[i] = field.Name;
if (field.GetValue(temp) is Array)
{
if ((field.GetValue(temp) as Array) != null)
{
int iMax = (field.GetValue(temp) as Array).Length;
for (int k = 0; k < iMax; k++)
{
if ((field.GetValue(temp) as Array).GetValue(k).GetType() is Enum)//枚举类型
{
}
else if ((field.GetValue(temp) as Array).GetValue(k) != null && (field.GetValue(temp) as Array).GetValue(k).GetType().IsPrimitive)//是否为基础类型
{
}
else if ((field.GetValue(temp) as Array).GetValue(k) is Array)
{
}
else//自定义结构类型
{
i++;
GetGNSSMessage((field.GetValue(temp) as Array).GetValue(k), k.ToString());
i--;
}
}
}
}
else
{
i++;
GetGNSSMessage(field.GetValue(temp), ctag);
i--;
}
Father[i] = "";
}
string Path = "";
for (int j = 0; j < Father.Length; j++)
{
if (Father[j] != "")
{
Path += Father[j] + ">";
}
else
{
break;
}
}
Console.WriteLine(Path + field.Name + "=" + field.GetValue(temp) + " " + ctag); //输出
//sw.WriteLine(Path + field.Name + "=" + field.GetValue(temp) + " " + ctag);
//sw.Flush();
MyTree.Add(Path + field.Name + "=" + field.GetValue(temp) + " " + ctag);
}
}
怎么调用:
for (int i = 0; i < Father.Length; i++)
{
Father[i] = "";
}
MyTree.Clear();
GetGNSSMessage(-结构体对象-, "");
可以用C#控件treeView来更直观的显示,点赞私信给显示代码