A:增加说明文档
This commit is contained in:
1 parent
b2f113e89f
commit
61e769a0f6
5 files changed
+360
-13
No files matched your search
@@ -149,20 +149,9 @@ public sealed class ConfigManager
|
||||
|
||||
public IList<ValidationResult> ValidateObject(object instance, bool throwOnError)
|
||||
{
|
||||
var context = new ValidationContext(instance);
|
||||
var results = new List<ValidationResult>();
|
||||
// validate top-level
|
||||
Validator.TryValidateObject(instance, context, results, validateAllProperties: true);
|
||||
|
||||
// validate nested properties with DataAnnotations recursively
|
||||
foreach (var prop in instance.GetType().GetProperties())
|
||||
{
|
||||
var value = prop.GetValue(instance);
|
||||
if (value is null) continue;
|
||||
if (IsSimple(prop.PropertyType)) continue;
|
||||
var nestedContext = new ValidationContext(value);
|
||||
Validator.TryValidateObject(value, nestedContext, results, validateAllProperties: true);
|
||||
}
|
||||
var visited = new HashSet<object>(ReferenceEqualityComparer.Instance);
|
||||
RecursiveValidate(instance, results, visited);
|
||||
|
||||
if (throwOnError && results.Count > 0)
|
||||
{
|
||||
@@ -172,6 +161,39 @@ public sealed class ConfigManager
|
||||
return results;
|
||||
}
|
||||
|
||||
private static void RecursiveValidate(object instance, IList<ValidationResult> results, HashSet<object> visited)
|
||||
{
|
||||
if (instance is null) return;
|
||||
if (!visited.Add(instance)) return;
|
||||
|
||||
var type = instance.GetType();
|
||||
if (IsSimple(type)) return;
|
||||
|
||||
var context = new ValidationContext(instance);
|
||||
Validator.TryValidateObject(instance, context, results, validateAllProperties: true);
|
||||
|
||||
foreach (var prop in type.GetProperties())
|
||||
{
|
||||
var value = prop.GetValue(instance);
|
||||
if (value is null) continue;
|
||||
var pType = value.GetType();
|
||||
if (IsSimple(pType)) continue;
|
||||
|
||||
if (value is System.Collections.IEnumerable enumerable && value is not string)
|
||||
{
|
||||
foreach (var item in enumerable)
|
||||
{
|
||||
if (item is null) continue;
|
||||
RecursiveValidate(item, results, visited);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
RecursiveValidate(value, results, visited);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsSimple(Type t)
|
||||
{
|
||||
t = Nullable.GetUnderlyingType(t) ?? t;
|
||||
|
||||
Reference in new issue
Block a user