0

为了在我的代码上设置选项严格打开,我在实际工作正常的代码上遇到错误。

    Public Function ModifyRegistryKey(ByVal rClass As String, ByVal rKey As String, ByVal rValName As String, ByVal rValue As String) As Integer

    'Grant Read, Write and Create permissions for the key
    Dim f As New RegistryPermission(RegistryPermissionAccess.Read Or _
                                    RegistryPermissionAccess.Write Or _
                                    RegistryPermissionAccess.Create, rKey)

    Dim regKey As Object
    Try
        'Check if it exists. If it doesn't it will throw an error
        regKey = My.Computer.Registry.CurrentUser.OpenSubKey(rKey, True).GetValue(rValName)
    Catch ex As Exception
        regKey = Nothing
    End Try

    If regKey Is Nothing Then
        'It doesn't exist here. Create the key and set the key name and value.
        regKey = My.Computer.Registry.CurrentUser.CreateSubKey(rKey)

        regKey.SetValue(rValName, rValue) 'LATE BINDING HERE

    Else
        'Registry key exists
        If Not regKey Is rValue Then
            My.Computer.Registry.SetValue(rClass & "\" & rKey, rValName, rValue)
        End If
    End If
End Function

为什么我收到错误消息:“Option Strict On 不允许后期绑定。” 以及如何在这里摆脱后期绑定?

4

1 回答 1

2

你已经声明regKey as Object然后你试图调用Microsoft.Win32.RegistryKey它的方法,但我猜编译器不知道它会是 type Microsoft.Win32.RegistryKey

顺便说一句,您的异常处理用法不是最佳实践,我假设异常正在发生,因为OpenSubKey()正在返回Nothing,但这不是异常,因此您应该为其编写代码。

我创建了一个我认为更好的示例,并且它确实可以编译 - 尽管我没有测试它,因为我不想确定我的注册表,而且我不确定为什么你有两种设置值的方法,所以我刚刚注释掉了你的第二种方式,可能是我在编辑注册表时缺少的东西......

Public Sub ModifyRegistryKey(ByVal rKey As String, ByVal rValName As String, ByVal rValue As String)
    Dim registryKey As Microsoft.Win32.RegistryKey

    registryKey = My.Computer.Registry.CurrentUser.OpenSubKey(rKey, True)

    If registryKey Is Nothing Then
        registryKey = My.Computer.Registry.CurrentUser.CreateSubKey(rKey)
    End If

    If registryKey.GetValue(rValName) Is Nothing _
    OrElse CStr(registryKey.GetValue(rValName)) <> rValue Then
        registryKey.SetValue(rValName, rValue)
        'My.Computer.Registry.SetValue(rClass & "\" & rKey, rValName, rValue)
    End If
End Sub
于 2013-10-18T13:27:23.600 回答