// 反射
// 一切从 type 开始 2 种拿到 type 的方式
// 作用:动态的操作对象 获取属性 方法 特性
// 1. 拿到对象的 type
// typeof(类);
// 2. 拿到实例化之后的对象的 type
var user = new User();
user.name = "zhansan";
var types = user.GetType();
// GetProperties() 获取所有的属性 GetProperty("id") 获取某个属性
types.GetProperties().ToList().ForEach(item => {
var name = item.name;
var id = item.id; // item.GetValue(user);
}); // 获取此对象的所有属性 并且遍历这些属性 然后使用 GetValue 获取这些属性的值
// 获取方法 GetMethod() 获取单个方法 GetMethods() 获取所有的方法
// 01 已知方法的名字
types.GetMethod("ToString");
// 02 未知方法的名字 Invoke 执行某个方法
types.GetMethod(nameof(User.ToString)).Invoke(user,null);
// 获取特性
types.GetCustomAttribute(typeof(TableAttribute));
// 获取id上的特性
types.GetProperties().ForEach(item => {
if(item.GetValue == "id") {
item.GetCustomAttribute(RequiredAttribute);
}
})
[Table("Users")]
class User {
[Required]
public int id { get; set; }
public string name { get; set; }
// 方法
public override string ToString() => $"{ID} -- {name}";
}