自定义特性标记类或属性,通过反射实现数据验证逻辑。
// 自定义必填特性 [AttributeUsage(AttributeTargets.Property)] public class RequiredAttribute : Attribute { } // 数据验证工具 public class DataValidator { public static bool Validate(object obj, out List<string> errors) { errors = new List<string>(); var properties = obj.GetType().GetProperties(); foreach (var prop in properties) { var requiredAttr = prop.GetCustomAttribute<RequiredAttribute>(); if (requiredAttr != null) { var value = prop.GetValue(obj); if (value == null || string.IsNullOrEmpty(value.ToString())) { errors.Add($"{prop.Name} 为必填项"); } } } return errors.Count == 0; } } // 测试实体 public class User { [Required] public string Name { get; set; } public int Age { get; set; } } // 调用示例 public static void TestAttribute() { var user = new User { Age = 25 }; if (!DataValidator.Validate(user, out var errors)) { foreach (var err in errors) Console.WriteLine(err); } }