如何遍历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));
}
}