c# - 'Microsoft.Win32.Registry' 是一个 'type' 但像 'variable' 一样使用

标签 c# vb.net c#-4.0

我正在尝试将一些 VB.net 代码转换为 C#,但在尝试转换这一行时遇到了问题。

VB.NET

Dim myreg As Microsoft.Win32.Registry

我知道它是静态的,所以我无法创建实例,但是当我尝试将 VB.NET 转换器转换为 C# 时,该网站给了我这个:

Microsoft.Win32.Registry myreg = null;

并给我一条错误消息:“Microsoft.Win32.Registry”是一个“类型”,但像“变量”一样使用

在VB.NET中Function的最后一部分,使用了myreg:

Finally
  myreg = Nothing
End Try

这是整个函数:

Imports System.Data.OleDb
Imports System.Data
Imports Microsoft.Win32.RegistryKey
Imports MyLogger 'custom reference, not worried about this.

Private Function getRegistryString(ByVal sVal As String, Optional ByVal sKey As String = "") As String
    Dim myreg As Microsoft.Win32.Registry
    Dim s As String
    Try
        s = myreg.LocalMachine.OpenSubKey(sKey).GetValue(sVal)
    Catch ex As Exception
        l.EventLog(ex.Message, EventLogEntryType.Error)
        Throw ex
    Finally
        myreg = Nothing
    End Try
    Return s
    s = Nothing
End Function

最佳答案

在 VB.NET 中,无法定义共享(静态)类。但是,在 C# 中,您可以指定一个类是静态的。当一个类是静态的时,它会强制其所有成员也是静态的。如果你试图声明一个静态类型的变量,编译器会给你一个错误。

然而,在 VB 中,由于没有共享类这样的东西,它总是允许您声明任何类型的变量,即使它完全没有意义,因为实例将没有成员。

无需将变量声明为 Registry 类型,您需要更改代码以简单地使用 Registry 类名本身。将变量设置为 Nothing 是没有意义的,因为变量从不存储对对象的引用。它总是Nothing

你的函数应该是这样的:

Private Function getRegistryString(ByVal sVal As String, Optional ByVal sKey As String = "") As String
    Dim s As String
    Try
        s = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(sKey).GetValue(sVal)
    Catch ex As Exception
        l.EventLog(ex.Message, EventLogEntryType.Error)
        Throw ex
    End Try
    Return s
End Function

关于c# - 'Microsoft.Win32.Registry' 是一个 'type' 但像 'variable' 一样使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11106181/

相关文章:

c# - 如何以编程方式训练 SpeechRecognitionEngine 并将音频文件转换为 C# 或 vb.net 中的文本

networking - C# 检测本地主机端口使用情况

java - 需要找到带有订单和订单详细信息的大代码

c# - 继承和构造函数中的错误

c# - 将 List<object> 转换为 List<Type>,类型在运行时已知

c# - 如何在 ASP.NET Core 2.1 出现第一个错误后停止验证

c# - 是否可以捕获线程开始和结束事件?

VB.NET For 循环函数作用域与 block 作用域

asp.net-mvc-4 - 如果用户尝试通过 URL 访问其他网站页面,如何在 C# MVC 4.5 中重定向已登录或未登录到登录页面的用户

c# - 如何使我的 URL 自定义?