(VB.NET)拥有一个具有单一功能的DLL。调用此函数会抛出nullreferenceexception,我无法理解是什么导致它

时间:2014-03-31 17:55:52

标签: vb.net dll nullreferenceexception

这是调用函数的代码:

Imports Peasantlish

    Public Class main
        Dim TranslateLib As Peasantlish.PeasantlishLib
        Private Sub Translate()
            Label2.Text = "Translator - working"
            TextBox1.Text = TranslateLib.TranslateToEng(TextBox2.Text)
        End Sub

TextBox2是包含要翻译的文本的文本框。 TextBox1包含结果。

这就是功能本身:

Imports System.Text.RegularExpressions

Public Class PeasantlishLib
    Public Function TranslateToEng(ByVal input As String)
        Dim output As String = "test string please ignore"
        output = input
        output = Regex.Replace(output, "full hd", "720p", RegexOptions.IgnoreCase)
        output = Regex.Replace(output, "fullhd", "720p", RegexOptions.IgnoreCase)
        output = Regex.Replace(output, "xbox live", "free service that I paid for", RegexOptions.IgnoreCase)
        output = Regex.Replace(output, "\bxbl\b", "free service that I paid for", RegexOptions.IgnoreCase)
        ' next are single words after phrases
        output = Regex.Replace(output, "\bhd\b", "720p", RegexOptions.IgnoreCase)
        output = Regex.Replace(output, "next gen", "already-was-on-pc-3-years-ago gen", RegexOptions.IgnoreCase)
        output = Regex.Replace(output, "censored", "bundle of sticks", RegexOptions.IgnoreCase)
        output = Regex.Replace(output, "gddr5", "high latency RAM", RegexOptions.IgnoreCase)
        output = Regex.Replace(output, "esram", "level 4 cache", RegexOptions.IgnoreCase)
        output = Regex.Replace(output, "Controller", "poo-ey excuse for an output device", RegexOptions.IgnoreCase)
        output = Regex.Replace(output, "console", "potato", RegexOptions.IgnoreCase)
        output = Regex.Replace(output, "cloud", "butt", RegexOptions.IgnoreCase)
        output = Regex.Replace(output, "optimization", "ultra low settings", RegexOptions.IgnoreCase)
        output = Regex.Replace(output, "optimized", "with ultra low settings", RegexOptions.IgnoreCase)
        ' and a bunch more of these
        Return output
    End Function
End Class

它在TextBox1.Text = TranslateLib.TranslateToEng(TextBox1.Text)行抛出异常。但我没有看到任何错误。在我将Regex.Replace的一堆迁移到.dll以实现整洁之前,它运行良好。输出变量之前是TextBox1.Text

2 个答案:

答案 0 :(得分:2)

您是否实例化了TranslateLib?我的VB有点生疏,但我认为你需要New关键字来实例化一个新对象:

Dim TranslateLib As New Peasantlish.PeasantlishLib

您可以通过查看哪个对象是Nothing(或null)在您的调试器中进行确认。如果它是TranslateLib,那么你从未实例化它。

答案 1 :(得分:0)

您需要在使用之前实例化TranslateLib:

Dim TranslateLib As Peasantlish.PeasantlishLib
...
TranslateLib = New Peasantlish.PeasantlishLib