2019/5/21

c# 列出所有類別中的屬性 ( Iterate through all class fields in C#)

I have  one example class like this:

public class Foo{
 public string Idno { get; set; }
 public string Phone{ get; set; }
public string Department{ get; set; }
}

 In order to bind database's  columns like EF,  I would like to iterate through these fields dynamically




using System.Reflection;



   Foo foo = new Foo();
            foo.Idno = "a12345678";
            foo.Department = "IT";

            foreach (PropertyInfo prop in typeof(Foo).GetProperties())
            {
                Response.Write(prop.Name + ";" + prop.GetValue(foo, null));
            }

沒有留言:

張貼留言