我可以引用变量而不是变量的实例吗?

时间:2014-10-15 02:21:42

标签: c#

我有以下两个类:

class MoveTo : Routine
{
    Creature creature;
    Entity target;

    public MoveTo(Creature Creature, Entity Target)
    {
        this.creature = Creature;
        this.target = Target;
    }

    public Act()
    {
        creature.MoveTowards(Target);
    }
}

......和......

class Creature
{
    Entity ClosestTarget { get; set; } 
    Routine currentBehavior;
    //...
}

我想要实现的目标是:

creature.ClosestTarget = OldClosestTarget;
Routine moveToClosestTarget = new MoveTo(creature, creature.ClosestTarget); //pass "ClosestTarget" as the "Target" parameter

//...

moveToClosestTarget.Act(); //Move towards OldClosestTarget
creature.ClosestTarget = NewClosestTarget;
moveToClosestTarget.Act(); //What I want: Move towards NewClosestTarget. What it actually does: Move towards OldClosestTarget

MoveTo例程中的引用对象将继续使用OldClosestTarget。

但对于这个特定的用例,我需要它反过来:我想专门传递给Creature.ClosestTarget变量,而不是对它当前包含的实例的引用。

我可以在C#中实现这个目标吗?

2 个答案:

答案 0 :(得分:2)

欺骗性的代码需要改变的代码如何:

class MoveTo : Routine
{
    Creature creature;
    Func<Entity> target;

    public MoveTo(Creature Creature, Func<Entity> Target)
    {
        this.creature = Creature;
        this.target = Target;
    }

    public Act()
    {
        creature.MoveTowards(Target());
    }
}

new MoveTo(creature, () => creature.ClosestTarget)

这是lambda演算中的经典惰性评估。

另一种方法是定义class Indirect<T> { public T Value; }并将ClosestTargetEntity更改为Indirect<Entity>,为MoveTo提供对同一Indirect<Entity>的引用然后,当Value的{​​{1}}发生更改时,两个类都会看到新值。

答案 1 :(得分:0)

public MoveTo(Creature Creature)
    {
        this.creature = Creature;
    }

    public Act()
    {
        creature.MoveTowards(this.creature.ClosestTarget);
    }

鉴于您的代码,您可以仅使用Creature对象进行初始化,并使用其ClosestTarget。虽然如果您在MoveTowards中使用Creature方法,为什么还要费心去传递Target?您可以使用ClosestTarget对象本身的Creature