先定义一个类:
public class User { public User() { Console.WriteLine($"{this.GetType().Name}被构造"); } public int Id { get; set; } public string Name { get; set; } public string ClassID; }
反射:
//常规写法赋值 { User user = new User(); user.Id = 123; user.Name = "张三"; user.ClassID = "1"; Console.WriteLine($"User.Name={user.Name}"); Console.WriteLine($"User.ClassID={user.ClassID}"); Console.WriteLine($"User.Id={user.Id}"); } //利用反射动态赋值 { Type type = typeof(User); //获取类型 object a = Activator.CreateInstance(type); //创建对象 foreach (var Prop in type.GetProperties())//GetProperties获取属性 { Console.WriteLine($"{type.Name}.{Prop.Name}={Prop.GetValue(a)}"); if (Prop.Name.Equals("Id")) { Prop.SetValue(a, 213);//设置值 } else if (Prop.Name.Equals("Name")) { Prop.SetValue(a,"张三"); } Console.WriteLine($"{type.Name}.{Prop.Name}={Prop.GetValue(a)}");//获取值 } foreach (var Field in type.GetFields())//GetFields获取字段 { Console.WriteLine($"{type.Name}.{Field.Name}={Field.GetValue(a)}"); if (Field.Name.Equals("ClassID")) { Field.SetValue(a, "213"); } Console.WriteLine($"{type.Name}.{Field.Name}={Field.GetValue(a)}"); } }