【问题标题】:InvokeMember give a different result than direct callInvokeMember 给出与直接调用不同的结果
【发布时间】:2013-07-10 12:17:53
【问题描述】:

我在 VB.NET 中调用 Shell.BrowseForFolder,因为我需要在 rootFolder 参数中传递任意路径。所以我实例化了一个这样的对象:

Dim shellType As Type = Type.GetTypeFromProgID("Shell.Application")
Dim shell = Activator.CreateInstance(shellType)

然后我打电话:

Dim folder = shell.BrowseForFolder(0, message, &H241, rootFolder)

它没有按预期工作(根文件夹F:未使用)

但如果我使用具有相同参数的反射:

Dim folder = shellType.InvokeMember("BrowseForFolder", _
  BindingFlags.InvokeMethod, Nothing, shell, New Object() {0, message, &H241, _
  rootFolder})

有效!

但对我来说,这 2 个调用(InvokeMember 和直接调用)应该会产生相似的结果(参数相同)。发生了什么事?

编辑:

事实上,如果我调用 ToString() 或者我放一个 litteral,它就可以工作:

Dim folder = shell.BrowseForFolder(0, message, &H241, rootFolder.ToString())

Dim folder = shell.BrowseForFolder(0, message, &H241, "F:")

但是如果 rootFolder 是一个参数,它就不起作用,例如:

Function BrowseForFolder(ByVal message As String, ByVal rootFolder As String) As String
    Dim shellType As Type = Type.GetTypeFromProgID("Shell.Application")
    Dim shell = Activator.CreateInstance(shellType)
    Dim folder = shell.BrowseForFolder(0, message, &H241, rootFolder)
    If folder Is Nothing Then
        Return ""
    End If
    Return folder.Self.Path
End Function

【问题讨论】:

    标签: .net vb.net reflection


    【解决方案1】:

    我在 Windows 7 64 位与 vs 2012 下重现此问题的唯一方法是在该变量中设置一个无效的 rootFolder,例如空字符串或废话数据。

    你能在那行做一个断点吗:

       Dim folder = shell.BrowseForFolder(0, message, &H241, rootFolder)
    

    并检查rootFolder 是什么?

    找到方法试试这个;

      Dim folder = shell.BrowseForFolder(0, message, &H241, rootFolder.ToString())
    

    我的代码:

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim rootFolder As Object = "f:"
        Dim shellType As Type = Type.GetTypeFromProgID("Shell.Application")
        Dim shell = Activator.CreateInstance(shellType)
        Dim folder = shell.BrowseForFolder(0, "message", &H241, rootFolder.ToString())
    End Sub
    

    【讨论】:

    • 同意,在 vs2010 上也无法在此处重现。,相同的操作系统。
    • 我在 Windows 7 64 位操作系统上使用 VS 2010。 rootFolder 是一个用“F:”初始化的字符串。此磁盘存在于我的计算机上。
    • @Maxence,我想我找到了解决方法,我能够重现该问题
    • @Maxence 将 rootFolder 替换为 rootFolder.ToString() 看起来很奇怪,但它可以工作。
    • @Maxence,对于那个...问微软,我不知道。
    【解决方案2】:

    您总是可以直接使用 folderBrowserDialog:

    Dim f As New FolderBrowserDialog
    f.SelectedPath = "f:"
    f.ShowDialog()
    

    虽然我看不到如何将它显示F:

    【讨论】:

    • 我正在使用 Shell.BrowseForFolder,因为 FolderBrowserDialog 只在其 RootFolder 属性中采用 SpecialFolder。
    • 当然——毕竟这是一个奇怪的限制。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多