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;
}
}
}
C#类反射,运行时创建类对象,读取设置属性值列子。
最新推荐文章于 2023-06-21 15:39:33 发布