這就是我,關於我的洛克人遊戲。我切換到組件系統,以便對象可以被數據驅動。這沒問題,但我遇到了問題。如何深度複製包含lambda表達式的對象?
我的對象有狀態,用輸入文件指定。這些國家有觸發器將它們轉換到其他國家。狀態改變的條件也在輸入文件中,並被解析成一個lambda表達式。現在我需要深度複製我的對象,並且我需要lambdas來引用副本的成員,而不是原始成員。程序加載時,原始文件會從文件中加載,但可以在任何時候複製(認爲是射擊)。
這裏的代碼大大簡化一下:
class StateComponent
{
// when the whole entity is cloned, it will get a clone of
// DependentComponent as well as a clone of this StateComponent.
private OtherComponent DependentComponent;
// there is a function to register dependencies. The entity that owns
// me also owns DependentComponent, and registered it with me.
public StateComponent Clone()
{
// what should I do here to make the lambda deep copied?
}
public void LoadFromXml(XElement node)
{
State state = new State();
LambdaExpression lambda = DynamicExpression.ParseLambda(from xml stuff)
Delegate condition = lambda.Compile();
Action effect = LoadTriggerEffect();
state.AddTrigger(condition, effect);
// add state to my list of states
}
private Action LoadTriggerEffect()
{
Action action = new Action(() => { });
if (some stuff from the input file)
action +=() => { DependentComponent.Foo(); DependentComponent.Bar = 5; }
return action;
}
}
還有更多比的是,觸發器實際上可能造成的狀態變化,然後將新狀態的初始化調用動作,但我在這裏簡化它。
所以問題是,當我深拷貝這個組件,或者嘗試無論如何,我不知道如何讓lambda表達式引用副本的DependentComponent實例,而不是原始的。我已經確定實體的深層副本正在獲取新的DependentComponent,但lambda只是引用原始的。委託一旦創建就基本鎖定到特定實例?我需要創建一個新的嗎?我不想再從文件中加載整個實體。
我其實已經想到了這一點,發佈後不少於1分鐘。但是我仍然對這個問題是否有一個通用的解決方案感興趣。 – Tesserex 2010-01-08 00:17:57