最近我开始使用游戏状态管理(详情:create.msdn.com/en-US/education/catalog/sample/game_state_management),这是用 XNA 制作的简单游戏的绝佳模板。
几天来我一直在分析它的实现,我对这种方法的LoadingScreen.cs有疑问:
/// <summary>
/// The constructor is private: loading screens should
/// be activated via the static Load method instead.
/// </summary>
private LoadingScreen(ScreenManager screenManager, bool loadingIsSlow,
GameScreen[] screensToLoad)
{
this.loadingIsSlow = loadingIsSlow;
this.screensToLoad = screensToLoad;
TransitionOnTime = TimeSpan.FromSeconds(0.5);
}
我不明白为什么会有参考分配:this.screensToLoad = screensToLoad;
。为什么不.Clone()
使用类似方法的东西呢?
[编辑]
好的...我认为我的问题不是 XNA 或游戏状态管理我准备了一段代码,并解释了我的疑问。
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace test
{
public class a
{
public int number = 3;
}
public class b
{
public a tmp;
public void f(a arg)
{
tmp = arg; // (*?*) isn't it dangerous assigning?
}
}
class Program
{
static void Main(string[] args)
{
b temp_b = new b();
{// (*!*) CODE BLOCK COMES HERE:
a temp_a = new a();
temp_b.f(temp_a);
temp_a.number = 4;
}
// TROUBLE EXPLANATION:
// We are outside of code block which I marked with (*!*)
// Now reference 'temp_a' is inaccessible.
// That's why line of code which I marked with (*?*) is dangerous.
// We saved 'temp_a' which is no longer accessible in 'temp_b' object.
//
// Now computer's memory pointed by reference, which is saved in 'temp_b.tmp' (and was saved in 'temp_a'),
// can be overriden by code which comes somewhere below this comment (or even in another thread or process).
//
// I think the same situation is in XNA GSM's piece of code.
// The only solution in my opinion is deep copy (AFAIK .Clone() can be implemented as shallow or deep copy).
Console.WriteLine(temp_b.tmp.number); // result is 4
// because we copied reference
// For me it's strange that this line was printed. As I mentioned above
// memory intended for 'temp_a' could be reused and overwritten.
}
}
}
为方便起见,此处使用相同的代码:ideone.com/is4S3。
我在上面的代码中提出了问题和疑问(见评论)。