考慮以下幾點:擴展方法不規則行爲
public static class FileSerializer
{
public static void SaveToFile<T>(this T obj, String fileName)
{
String dbFile = Path.Combine(Application.StartupPath, fileName);
using (Stream stream = File.Open(dbFile, FileMode.Create))
{
BinaryFormatter bFormatter = new BinaryFormatter();
lock (obj) bFormatter.Serialize(stream, obj);
}
}
public static void LoadFromFile<T>(this T obj, String fileName, Boolean ensureExists)
{
String dbFile = Path.Combine(Application.StartupPath, fileName);
if (!File.Exists(dbFile))
if (ensureExists)
throw new FileNotFoundException("File not Found!");
else return;
using (Stream stream = File.Open(dbFile, FileMode.Open))
{
if (stream.Length > 0)
{
BinaryFormatter bFormatter = new BinaryFormatter();
obj = (T)bFormatter.Deserialize(stream);
}
}
}
}
即使我附加調試器,和OBJ在上面的代碼的最後一行,有記錄,當我使用的方法,例如:
lstServers.LoadFromFile("Servers.dat", false);
lstServers is ALWAYS空。
任何想法爲什麼?
任何評論可用於downvote? – Oliver 2011-04-21 14:04:44
不是我downvote。 – 2011-04-21 14:08:48
不是我的失望,但我懷疑它與一個對大多數字符串無效的方法造成字符串實例的污染有關。最好把它做成香草靜態方法。 – Jamiec 2011-04-21 14:16:52