C#類反射,執行時建立類物件,讀取設定屬性值列子。
阿新 • • 發佈:2018-12-26
using System; using System.Reflection; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { //View class Program { static void Main(string[] args) { StudentBll<Student> studentBll = new StudentBll<Student>(); Student model = studentBll.GetModelByID(1); Console.WriteLine(model.Key + " " + model.Name + " " + model.Age); Console.WriteLine("請按下鍵盤任意鍵退出!"); Console.ReadKey(); } } //model public class Student { public int Key { get; set; } public string Name { get; set; } public int Age { get; set; } } //control public class StudentBll<T> where T:class,new() { public T GetModelByID(int ID) { T model=null; model = Activator.CreateInstance(typeof(T), true) as T;//根據型別建立例項 PropertyInfo[] _PropertyInfo = model.GetType().GetProperties();//讀取屬性集合 foreach(PropertyInfo p in _PropertyInfo)//迴圈賦值 { if (p.Name == "Name") p.SetValue(model, "kelly"); else if (p.Name == "Age") p.SetValue(model, 15); else if (p.Name == "Key") p.SetValue(model, ID); } return model; } } }