My.Computer.FileSystem
和System.IO.File
命名空间中有很多功能重复。
那么它们之间到底有什么不同呢?
My.Computer.FileSystem.CopyFile(source, dest, True)
并且:
System.IO.File.Copy(source, dest, True)
有性能差异吗?大家对哪个更易读的意见是什么?我个人使用
My.Computer
命名空间,但现在只是习惯而已。My.Computer.FileSystem
和System.IO.File
命名空间中有很多功能重复。
那么它们之间到底有什么不同呢?
My.Computer.FileSystem.CopyFile(source, dest, True)
并且:
System.IO.File.Copy(source, dest, True)
My.Computer
命名空间,但现在只是习惯而已。我的"*"只是一个针对VB.NET实现的外观模式类集,包含常见的System.IO*(以及其他)操作。由于需要经过额外的抽象层,所以会有非常微小的性能损失,但您必须决定是否值得为此进行优化。我建议您使用在您和您团队中最合适的方式。
如果您使用 .NET Reflector 检查My.Computer.FileSystem.CopyFile
代码,则会发现该方法封装了许多 System.IO 类,例如 File 和 Directory,特别是 File 类的 Copy、Move 和 Delete 方法。示例:
'lots of other code snipped out for brevity and to show the use of System.IO classes...
Directory.CreateDirectory(FileSystem.GetParentPath(str))
'snip
If
' snip
Else
File.Delete(str)
File.Move(path, str)
End If
Else
File.Move(path, str)
End If
End Sub
My.Computer
是在 VB 中添加的更方便和易于理解的抽象层,用于底层功能。 它的一些方法添加了新功能,这只有在需要使用 System.IO.File
时才会使用它。My.Computer
的 Network.DownloadFile 方法,其中它具有向用户显示对话框的功能:
如果您已经在某些地方使用过如果将 showUI 设置为 True,则会出现对话框, 显示操作的进度;对话框包含一个 取消按钮,可用于取消操作。 对话框 不是模态的,因此不会阻止程序中其他窗口的用户输入。
System.IO.File
,出于一致性原因,强烈建议不要在其上使用 My.Computer
。也就是说,不要混合调用 My.Computer
和 System.IO.File
中的方法,应该坚持使用一个命名空间!My.Computer
是为初学者添加到VB中的” - 这是无稽之谈。这从未是它的规定用途。相反,它是一个“便利层”,没有什么不好使用它。但有些功能确实完全重复了,这有点不太幸运。 - Konrad RudolphSystem.IO.*
更多的功能。我从未打算让我的有关初学者的声明成为一个如此直接的陈述。 - Rudi VisserSystem.IO.Directory.Delete
并且
FileSystem.DeleteDirectory
System.IO.Directory.Delete
FileSystem.DeleteDirectory
My.Computer.FileSystem.CopyFile("source", "destination")
It will actually call the Microsoft.VisualBasic.FileIO.FileSystem.CopyFile
method. So while it's true that the My
namespace is not exclusively a VB6 compatibility layer, it does contain methods that are intended to make the transition from VB6 to .Net easier.
My.Computer.FileSystem.CopyFile(source, dest)
这将导致以下一系列事件
MyProject.Computer.FileSystem.CopyFile
将被嵌入应用程序中MyProject
和MyComputer
将生成到程序集中MyComputer
类型仅从Microsoft.VisualBasic.Devices.Computer
派生FileSystem.CopyFile
方法解析为FileSystemProxy.CopyFile
,它只是转发到FileSystem.CopyFile
Microsoft.VisualBasic
命名空间混淆了。有两件事情反驳了你的理论:①该命名空间是在VB.NET的较晚版本中添加的,②它并没有特别接近复制VB6的功能(除了My.Forms
)。 - Konrad RudolphMy.Computer.FileSystem
调用会生成到目标程序集中,并且它们会转发到 Microsoft.VisualBasic
。你可以使用反编译工具验证这一点。 - JaredPar"a" = "b"
)也会生成依赖于 Microsoft.VisualBasic
的代码,这并不是一个论据。 - Konrad RudolphMy.Computer.FileSystem
实际上是转发到 Microsoft.VisualBasic.FileSystem
,这部分旨在为 VB6 用户提供兼容性层。 - JaredParMy.Computer.FileSystem
最终会转发到 M.VB.FileIO.FileSystem
。我原本以为这两种类型都是兼容性层的一部分。尤其是 FileIO.FileSystem
方法。 - JaredPar使用 System.IO.File.Delete 与 My.Computer.FileSystem.DeleteFile 相比确实有所不同:
如果 a_file 不存在,My.Computer.FileSystem.DeleteFile(a_file) 会抛出 FileNotFoundException 异常,而 System.IO.File.Delete(a_file) 不会。
只有当 a_file 中包含的路径不存在时,System.IO.File.Delete 才会抛出 DirectoryNotFoundException 异常。
My
类,但如果您发现它方便,那么绝对没有任何问题。这就是整个目的,在常见情况下加快开发速度。 - Cody Gray