如有个struct结构方法:public struct User
{
   public int id;
   public string name;
   ........
}
要求获取遍历出user里面的所有属性值。

解决方案 »

  1.   

    refer : http://blog.csdn.net/superhoy/article/details/7766856
      

  2.   

    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
                }
            }
      

  3.   


    谢谢,这样是可以的。
    我想再请问下如果我想写个通用的方法效果这样:User u = new User(){
     id=1,
     name="1"
     ......
    }
    GetVal(u);public void GetVal(object obj){
    foreach(var o in obj){
    Console.WriteLine("key"+o.key+"value"+o.value);
    }
    }这个SetVal函数应该怎样写呢?
      

  4.   


    谢谢
    我想再请问下如果我想写个通用的方法效果这样:
    User u = new User(){
     id=1,
     name="1"
     ......
    }
    GetVal(u);public void GetVal(object obj){
    foreach(var o in obj){
    Console.WriteLine("key"+o.key+"value"+o.value);
    }
    }这个GetVal应该怎样写呢?
      

  5.   

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

  6.   


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

  7.   

    结合各位所说的问题最终解决了:public struct User
    {
       public int id;
       public string name;
       ........
    }----------------------------User u = new User(){
     id=1,
     name="1"
     ......
    }
    SetVal(typeof(User) ,(object)user);------------------------------------------public void SetVal(Type type, object obj)
    {
    FieldInfo[] fileds = type.GetFields();
    foreach (FieldInfo p in fileds)
    {
    Console.WriteLine("key:"+p.Name+"value:"+p.GetValue(obj).ToString());
    }
    }