这样:
1: public static IEnumerable<ErrorInfo> GetErrors(this object instance)
2: {
3: //或返回一个只包含一个ErrorInfo对象的集合
4: if (instance == null) return null;
5:
6: //尝试获取类型的伙伴类型
7: var metadataAttrib = instance.GetType().GetCustomAttributes(typeof(MetadataTypeAttribute), true).OfType<MetadataTypeAttribute>().FirstOrDefault();
8: //获取具有校验数据 的类型(伙伴类型或本类型)
9: var buddyClassOrModelClass = metadataAttrib != null ? metadataAttrib.MetadataClassType : instance.GetType();
10: //伙伴类型的属性
11: var buddyClassProperties = TypeDescriptor.GetProperties (buddyClassOrModelClass).Cast<PropertyDescriptor>();
12: //实际模型的属性
13: var modelClassProperties = TypeDescriptor.GetProperties(instance.GetType ()).Cast<PropertyDescriptor>();
14:
15: //获取伙伴类型或本类型的校验特性
16: var buddyClassAttrib = TypeDescriptor.GetAttributes (buddyClassOrModelClass).OfType<ValidationAttribute>();
17: var modelClassAttrib = TypeDescriptor.GetAttributes(instance.GetType ()).OfType<ValidationAttribute>();
18:
19: var errors = (
20: from buddyProp in buddyClassProperties
21: join modelProp in modelClassProperties on buddyProp.Name equals modelProp.Name
22: from attribute in buddyProp.Attributes.OfType<ValidationAttribute> ()
23: where !attribute.IsValid(modelProp.GetValue(instance))
24: select new ErrorInfo(buddyProp.Name, attribute.FormatErrorMessage(string.Empty), instance)
25: ).Union (
26: from attribute in buddyClassAttrib
27: where !attribute.IsValid(instance)
28: select new ErrorInfo(string.Empty, attribute.FormatErrorMessage(string.Empty), instance)
29: ).Union(
30: from attribute in modelClassAttrib
31: where !attribute.IsValid(instance)
32: select new ErrorInfo(string.Empty, attribute.FormatErrorMessage (string.Empty), instance)
33: );
34:
35: return errors;
36: }
37:
|