我创建了一个打算检查的类,Generic T符合所有要求的规范。需要帮助来聚合它们并返回布尔值。
这是基本规范类
/// <summary>
/// Base spec
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class BaseSpecification<T>
{
public abstract Expression<Func<T, bool>> ToExpression();
/// <summary>
/// Meets
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public bool Meets(T entity)
{
Func<T, bool> predicate = ToExpression().Compile();
return predicate(entity);
}
}
具体说明基础:
public class DeviceIsActiveSpecification : BaseSpecification<Device>
{
public override Expression<Func<Device, bool>> ToExpression()
{
//Устройство поддерживает выполнение команд (Активное)
return device => device.DeviceActivityType == DeviceActivityType.Active;
}
}
必须检查的验证器类是否满足所有cpecifications:
public class SpecificationValidator<T>
{
/// <summary>
/// Cpec list
/// </summary>
private readonly IList<BaseSpecification<T>> _specifications2Meet;
public SpecificationValidator()
{
_specifications2Meet = new List<BaseSpecification<T>>();
}
/// <summary>
/// Add cpec
/// </summary>
/// <typeparam name="TSecification"></typeparam>
/// <returns></returns>
public SpecificationValidator<T> Add<TSecification>() where TSecification : BaseSpecification<T>, new()
{
return Add(new TSecification());
}
/// <summary>
///
/// </summary>
/// <param name="specification"></param>
/// <returns></returns>
SpecificationValidator<T> Add(BaseSpecification<T> specification)
{
if (specification == null) throw new ArgumentNullException(nameof(specification));
_specifications2Meet.Add(specification);
return this;
}
/// <summary>
/// Meets all
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public bool MeetsAllSpecifications (T source)
{
??? Need help here to agregate "Meets"
}
}
预期用途:
var validator = new SpecificationValidator<Device>()
.Add<DeviceIsActiveSpecification>()
.Add<CommunicationDeviceSpecification>()
.MeetsAllSpecifications(device);
任何帮助表示赞赏!谢谢!
答案 0 :(得分:2)
也许我错过了一些东西,但似乎你可以在这里简单地使用LINQ&#39; All
:
public bool MeetsAllSpecifications (T source)
{
return specifications2Meet.All(spec => spec.Meets(source));
}