ラムダ式についてなぜか微妙に勘違いしていたのでメモ。
キャラクターを表すクラスにキャラクターの位置を表す Position 、キャラクターの1回の移動量を返す getMovement というメンバ変数がある。
using System;
using Microsoft.Xna.Framework;
class Character
{
public Vector2 Position { get; set; }
private Func<Vector2> getMovement;
public Character()
{
getMovement = () => new Vector2(1, (float)Math.Sin(Position.X));
}
public void Update()
{
Position += getMovement();
}
}メインループで Update を実行すると getMovement の内容に応じて Position が変化する。
そして勘違いしていたのは getMovement のラムダ式で Position を使っている部分。
ここで Position は getMovement への代入時の値がそのままで Position が変わってから getMovement を実行しても同じ結果が返ってくると思ってた。
別にそんな事はなかった。
遅延評価って難しい。