1、什么是反射
在.net程序運行的時候會將各種對象中的數據、對象的名稱、對象的類型這些信息保存在元數據中,元數據保存在程序集中,我們訪問並操作元數據或者程序集的行為就叫反射。舉個栗子:我們在代碼中實例化的對象是一座房子,但是程序編譯運行時的基本單位不是房子,而是磚。程序把這座房子解析成了一塊塊磚,我們訪問、操作這些磚需要把它還原成一座房子。具體來說,把一個對象解析成元數據,再把元數據還原成另一個對象的行為叫反射,但是只要訪問了,就使用了對象,所以我說訪問並操作元數據或者程序集的行為就叫反射。當然了,這是個人理解。
2、如何使用反射
使用GetType()或者typeof()方法獲取一個type類,這個類就包含了該對象的所有信息。下面用代碼舉例一些反射的基本用法:
/// <summary> /// 反射用的類 /// </summary> public class TypeofModel { [Description("這是id")] public int Id { get; set; } [Description("這是編碼")] public string No { get; set; } } //下面是調用的代碼 var typeofModel = new TypeofModel() { Id = 1, No = "第一" }; var t = typeofModel.GetType(); var cols = t.GetFields();//獲取所有字段 var properties = t.GetProperties();//獲取所有屬性 foreach (var v in properties) { string str = ""; str += v.Name;//獲取屬性名稱 str += v.PropertyType;//獲取屬性類型 str += v.GetValue(typeofModel);//獲取屬性值 object[] attributes = v.GetCustomAttributes(true);//獲取該屬性值的所有特性 foreach (var m in attributes) { var childProperties = m.GetType().GetProperties();//獲取所有屬性 foreach (var n in childProperties) { str += n.GetValue(m);//獲取屬性值 } } }
3、反射的應用場景
保存數據的時候可以使用反射驗證數據的簡單信息,這里我們只驗證string類型,代碼如下:
public class ValidationAttribute : Attribute { public ValidationAttribute(int maxLength, string name, bool isRequired) { MaxLength = maxLength; Name = name; IsRequired = isRequired; } public int MaxLength { get; set; } public string Name { get; set; } public bool IsRequired { get; set; } } public static class ValidationModel { public static (bool,string) Validate(object obj) { var t = obj.GetType(); var properties = t.GetProperties();//獲取所有屬性 foreach (var property in properties) { if (!property.IsDefined(typeof(ValidationAttribute), false)) continue;//驗證是否加上ValidationAttribute標記 object[] objs = property.GetCustomAttributes(typeof(ValidationAttribute), true);//獲取特性 var firstValidation = (ValidationAttribute)objs[0]; var maxLength = firstValidation.MaxLength; var name = firstValidation.Name; var isRequired = firstValidation.IsRequired; //獲取屬性的值 var propertyValue = property.GetValue(obj) as string; if (string.IsNullOrEmpty(propertyValue) && isRequired) { return (false, $"{name}不可為空"); } if (!string.IsNullOrEmpty(propertyValue) && propertyValue.Length > maxLength) { return (false, $"{name}長度不可超過{maxLength}"); } } return (true,""); } }
/// <summary> /// 反射用的類 /// </summary> public class TypeofModel { [Description("這是id")] public int Id { get; set; } [Validation(64,"編碼",true)] public string No { get; set; } }
var model = new TypeofModel() { Id = 1, No = "" }; var msg = ValidationModel.Validate(model); if (!msg.Item1) { throw new Exception(msg.Item2); }