我有recently learned如何使用lambda进行惰性评估,这使我可以这样做:
MoveTo moveToTargetCreature =
new MoveTo(() => parent.Context.TargetCreature);
...
public class MoveTo
{
Func<Creature> Target { get; set; }
public MoveTo(Func<Creature> Target)
{
this.Target = Target;
}
public Act(Creature parent)
{
parent.MoveTowards(Target().Position);
}
}
...稍后调用例程Act()方法,使生物移动到最近的目标。
当我想要做的就是检索一个变量(只是调用Target())时这很好用,但是如果我想设置它呢?例如:
SetVariable setTargetCreatureToClosestCreature =
new SetVariable(parent.Context.TargetCreature, () => parent.Context.ClosestCreature);
...
public class SetVariable
{
Creature VariableToSet { get; set; }
Func<Creature> Target { get; set; }
public SetVariable(Creature VariableToSet, Func<Creature> Target)
{
this.VariableToSet = VariableToSet;
this.Target = Target;
}
public Act(Creature parent)
{
VariableToSet = Target();
//What I want: Set "parent.Context.TargetCreature" to Target()
//What it does: Sets the internal "VariableToSet" to Target(), but
//leaves "parent.Context.TargetCreature" as what it was when initialised.
}
}
如果我选择使用Func和lambda语法,它将无法编译,因为你无法分配给方法调用。
这是什么样的合适语法?
答案 0 :(得分:1)
也许这就是你想要的?
public class SetVariable
{
Creature ObjectToSet { get; set; }
Action<Creature, Creature> SetterAction { get; set; }
public SetVariable(Creature objectToSet, Action<Creature, Creature> setterAction)
{
this.ObjectToSet = objectToSet;
this.SetterAction = setterAction;
}
public Act(Creature parent)
{
this.SetterAction(parent, this.ObjectToSet);
//the setter action would be defined as (when instantiating this object):
//SetVariable mySet = new SetVariable(null, (target, val) => target.PropertyName = val);
//it will set the PropertyName property of the target object to val (in this case val=null).
}
}