2013-10-18 45 views
0

爲了在我的代碼上設置選項strict ON,我得到的代碼實際上工作正常。對設置註冊表值的後期綁定

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禁止延遲綁定」。以及如何擺脫這裏的後期綁定?

+0

閱讀:http://stackoverflow.com/questions/ 12375405/option-strict-on-disallows-late-binding –

+0

我願意。但仍然無法解決問題。 –

回答

2

你已經聲明regKey as Object,然後你試圖調用Microsoft.Win32.RegistryKey方法,但我猜編譯器不知道它將是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 
+0

是的,我非常喜歡它。謝謝你可行的例子。 –