1
我有一個scneario,我想用反射來使用FluentValidation進行驗證。成纔是這樣的:對象的如何在FluentValidation中使用反射?
public class FooValidator : AbstractValidator<Foo>
{
public FooValidator(Foo obj)
{
// Iterate properties using reflection
var properties = ReflectionHelper.GetShallowPropertiesInfo(obj);
foreach (var prop in properties)
{
// Create rule for each property, based on some data coming from other service...
//RuleFor(o => o.Description).NotEmpty().When(o => // this works fine when foo.Description is null
RuleFor(o => o.GetType().GetProperty(prop.Name)).NotEmpty().When(o =>
{
return true; // do other stuff...
});
}
}
}
的調用ReflectionHelper.GetShallowPropertiesInfo(obj)
回報「淺」的屬性。然後,爲每個屬性創建一個規則。 這是我對象獲取屬性代碼:
public static class ReflectionHelper
{
public static IEnumerable<PropertyInfo> GetShallowPropertiesInfo<T>(T o) where T : class
{
var type = typeof(T);
var properties =
from pi in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
where pi.PropertyType.Module.ScopeName == "CommonLanguageRuntimeLibrary"
&& !(pi.PropertyType.IsGenericType && pi.PropertyType.GetGenericTypeDefinition() == typeof(ICollection<>))
select pi;
return properties;
}
}
此代碼編譯並可以執行
IValidator<Foo> validator = new FooValidator(foo);
var results = validator.Validate(foo);
但它不能正常工作(驗證永遠不會失敗)。有什麼辦法可以做到這一點?
注意:演示代碼,可以發現INT在Github上FluentValidationReflection