在C#中使用使用和获取内部变量

Mad*_*Boy 2 c# using

我一直认为通过声明var之前using允许将其分配到内部using然后我仍然可以读取它之外的变量.结果我不能:-)

ReadOnlyCollection<string> collection;
using (var archive = new SevenZipArchive(varRarFileName)) {
    collection = archive.Volumes;
    MessageBox.Show(collection.Count.ToString());  // Output 10
}
MessageBox.Show(collection.Count.ToString()); // output 0
Run Code Online (Sandbox Code Playgroud)

任何方式使它工作而不停止使用 using

全面测试方法:

private ReadOnlyCollection<string> ExtractRar(string varRarFileName, string varDestinationDirectory) {
    ReadOnlyCollection<string> collection;
    using (var archive = new SevenZipArchive(varRarFileName)) {
        collection = new ReadOnlyCollection<string>(archive.Volumes); 
        MessageBox.Show(collection.Count.ToString()); // output 10
    }
    MessageBox.Show(collection.Count.ToString()); // output 0
    return collection;
}
Run Code Online (Sandbox Code Playgroud)

Joe*_*eau 6

复制archive.Volumes而不是只有集合引用它.然后,在使用结束时处理存档时,您的收藏将不会被处理.


Lee*_*Lee 5

正如乔尔·龙多(Joel Rondeau)在回答中指出的那样,在收集存档文件时,该收藏品正在被清除.但是,将它包装在一个ReadonlyCollection将无法正常工作,因为这不会复制包装列表.您需要手动创建此副本:

ReadOnlyCollection<string> collection;
using (var archive = new SevenZipArchive(varRarFileName))
{
    collection = new ReadOnlyCollection<string>(archive.Volumes.ToList());
}
Run Code Online (Sandbox Code Playgroud)