我需要为不同的“配置对象”编写一个类,其中包含“if xyz = 5 then ..”以将一些规则和操作转移到这些规则。
任何人都可以帮我一个聪明的类似课程设计吗?
我正在使用C#.NET 3.5
答案 0 :(得分:2)
如果您引用的规则应映射到操作,那么您可以拥有这样的类:
interface IRule<T>
{
void Apply(T obj);
}
class PredicateRule<T> : IRule<T>
{
public ActionRule(Func<T, bool> p, Action<T> a)
{
this.predicate = p;
this.action = a;
}
readonly Func<T, bool> predicate;
readonly Action<T> action;
public void Apply(T obj)
{
if (this.predicate(obj))
this.action(obj);
}
}
那么你的“if xyz = 5 then ..”规则可以这样声明:
var r = new PredicateRule<XyzClass>(x => x == 5, x => { //then... });
答案 1 :(得分:0)
不确定你在追求什么,但你可以有一个可覆盖的SetDefaults()方法来创建一个对象和类似的ApplyRules()方法来执行操作,以便在保存对象之前执行操作?