我一开始就被一个看似非常简单的任务所困扰。我有一个类层次结构,每个类都可以在其中定义自己的验证规则。定义验证规则应该尽可能简单。这几乎是需要的:
class HierarchyBase
{
private List<Func<object, bool>> rules = new List<Func<object, bool>>();
public int fieldA = 0;
public HierarchyBase()
{
AddRule(x => ((HierarchyBase)x).fieldA % 2 == 0);
}
protected virtual void Operation()
{
fieldA++;
}
protected void AddRule(Func<object, bool> validCriterion)
{
rules.Add(validCriterion);
}
public void PerformOperation()
{
Operation();
Validate();
}
protected virtual void Operation()
{
fieldA++;
}
private void Validate()
{
IsValid = rules.All(x => x(this));
}
public bool IsValid
{
get;
private set;
}
}
还需要一件事 - 添加验证规则时的类型安全。否则每个子类将不得不做那些看起来很尴尬的演员表。理想情况下Func<T, bool>
会起作用,但有一大堆问题:我们不能HierarchyBase
从任何类型继承我们的,IValidatable<HierarchyBase>
因为继承层次结构可以是 N 级深(是的,我也感觉到气味);存储任何混凝土Func<HierarchyBaseInheritor, bool>
并rules
遍历它们。
您将如何在这里介绍类型安全?