读书人

怎么遍历struct

发布时间: 2013-09-06 10:17:17 作者: rapoo

如何遍历struct
如有个struct结构方法:


public struct User
{
public int id;
public string name;
........
}


要求获取遍历出user里面的所有属性值。
[解决办法]
public struct User
{
public int id;
public string name;
}

 static void Main(string[] args)
{
Type type = typeof(User);
FieldInfo[] fileds = type.GetFields();
foreach (FieldInfo f in fileds)
{
Console.WriteLine(f.Name);//id name
}
}

[解决办法]

public void GetVal(object obj)
{
Type type = obj.GetType();
PropertyInfo[] pros = type.GetProperties();
foreach (PropertyInfo p in pros)
{
Console.WriteLine(p.GetValue(obj, null));
}
}

读书人网 >C#

热点推荐