首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

怎么遍历struct

2013-09-06 
如何遍历struct如有个struct结构方法:public struct User{public int idpublic string name........}要

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

热点排行