爲什麼不只是有一個名爲類似「constants.bin」文件的存在,你的C#程序檢查。如果該文件不存在,則讓它生成數組並將其序列化爲「constants.bin」。如果該文件確實存在,那麼就使用串行讀回。
int[,] constants;
if(!File.Exists("constants.bin")) {
GenerateConstants();
Stream stream = new FileStream("constants.bin", FileMode.Create, FileAccess.Write, FileShare.None);
new BinaryFormatter.Serialize(stream, constants);
stream.Close();
}
else
{
Stream stream = new FileStream("constants.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
constants = (int[,])(new BinaryFormatter.Deserialize(stream));
stream.Close();
}
我沒有測試過這一點,所以你可能需要調整它一點點。
第一次運行C#應用程序時,「constants.bin」將不存在,因此它將生成二維數組,然後將其序列化到文件中。程序的每次後續運行都會找到「constants.bin」文件並將其反序列化爲本地二維數組。
我最初考慮過這個問題。但是,預先計算並將值存儲在另一個文件中的主要好處是腳本不必每次運行應用程序時都運行。對於IronPython,我不得不每次運行腳本都要調用這個腳本,這樣做會破壞在主程序之外移動計算的目的。 – Mandelbrot 2010-07-28 18:11:24