尝试将从二进制文件读取的元素添加到BindingList<Type>
. 这是错误的代码:
BindingList<Type> tmpList = null;
using (FileStream serializedListStream = File.OpenRead(_kReificableDroidsListPath))
{
BinaryFormatter serializer = new BinaryFormatter();
//Temporary list so that ListChanged event is fired
//upon adding new types
tmpList = serializer.Deserialize(serializedListStream) as BindingList<Type>;
foreach (Type droidType in tmpList)
{
ReificableDroids.Add(droidType);
}
}
Visual Studio 调试器向我显示此异常:
System.IO.IOException: The process cannot access the file 'C:\Users\Zoneur\documents\visual studio 2012\Projects\Droid TP1\Droid TP2\bin\Debug\reificable_droids_list.bin' because it is being used by another process.
我的理解是该文件需要关闭,所以我将foreach
循环从using
语句中取出,如下所示:
BindingList<Type> tmpList = null;
using (FileStream serializedListStream = File.OpenRead(_kReificableDroidsListPath))
{
BinaryFormatter serializer = new BinaryFormatter();
//Temporary list so that ListChanged event is fired
//upon adding new types
tmpList = serializer.Deserialize(serializedListStream) as BindingList<Type>;
}
foreach (Type droidType in tmpList)
{
ReificableDroids.Add(droidType);
}
不再抛出异常,但我不明白问题是什么......ReificableDroids
是 type 的属性BindingList<Type>
。
另外,如果我将foreach
循环保留在using
语句中,并且只将类型名称打印到控制台,如下所示:
foreach (Type droidType in tmpList)
{
Console.WriteLine(droidType.GetType().ToString());
}
也没有抛出异常。
有谁知道什么可能导致在 using 语句中引发此异常?