gpt4 book ai didi

.net - InvokeMember 给出与直接调用不同的结果

转载 作者:行者123 更新时间:2023-12-04 14:42:05 31 4
gpt4 key购买 nike

我在 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:)

Direct call

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

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

有效!

Reflection

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

编辑:

事实上,如果我调用 ToString() 或输入一个乱码,它会起作用:

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

最佳答案

我在 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

关于.net - InvokeMember 给出与直接调用不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17570463/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com