【问题标题】:Member '<method>' cannot be accessed with an instance reference无法使用实例引用访问成员“<method>”
【发布时间】:2011-09-16 22:30:10
【问题描述】:

整个错误文本是:

成员'System.Text.RegularExpressions.Regex.Replace(string, string, string, System.Text.RegularExpressions.RegexOptions)'不能通过实例引用访问;改为使用类型名称来限定它

这是代码。我在这里的另一篇文章中删除了“静态”,但它仍然给我错误。

感谢所有专家的帮助 - 谢谢!

public string cleanText(string DirtyString, string Mappath)
{
    ArrayList BadWordList = new ArrayList();
    BadWordList = BadWordBuilder(BadWordList, Mappath);

    Regex r = default(Regex);
    string element = null;
    string output = null;

    foreach (string element_loopVariable in BadWordList)
    {
        element = element_loopVariable;
        //r = New Regex("\b" & element)
        DirtyString = r.Replace(DirtyString, "\\b" + element, "*****", RegexOptions.IgnoreCase);
    }

    return DirtyString;
}

【问题讨论】:

标签: c# instance


【解决方案1】:

问题在于使用方法Replace 而不是在声明中使用静态。您需要使用类型名Regex 而不是变量r

DirtyString = Regex.Replace(DirtyString, "\\b" + element, "*****", RegexOptions.IgnoreCase);

原因是在 C# 中,您无法通过类型的实例访问 static 方法。这里Replace 是static 因此它必须通过Regex 类型使用

【讨论】:

    【解决方案2】:

    好的,首先; default(Regex) 将简单地返回 null,因为 Regex 是一个引用类型。因此,即使您的代码已编译,它肯定会在这一行出现 NullReferenceException 崩溃,因为您从未将任何有效的东西分配给 r。

    DirtyString = r.Replace(DirtyString, "\\b" + element, "*****", RegexOptions.IgnoreCase);
    

    接下来,编译器会准确地告诉您问题所在; Replace 是静态方法,不是实例方法,所以需要使用类型名而不是实例变量。

    DirtyString = Regex.Replace(...);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-19
      • 2021-11-26
      相关资源
      最近更新 更多