C# 成员'&书信电报;方法>';无法使用实例引用访问

C# 成员'&书信电报;方法>';无法使用实例引用访问,c#,instance,C#,Instance,整个错误文本为: 无法使用实例引用访问成员System.Text.RegularExpressions.Regex.Replace(string,string,string,System.Text.RegularExpressions.RegexOptions);改为使用类型名称限定它 这是密码。我在这里删除了另一篇文章中提到的“static”,但它仍然给了我错误 我非常感谢这里所有专家的帮助-谢谢 public string cleanText(string DirtyString, stri

整个错误文本为:

无法使用实例引用访问成员System.Text.RegularExpressions.Regex.Replace(string,string,string,System.Text.RegularExpressions.RegexOptions);改为使用类型名称限定它

这是密码。我在这里删除了另一篇文章中提到的“static”,但它仍然给了我错误

我非常感谢这里所有专家的帮助-谢谢

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;
}

问题在于使用方法
Replace
而不是在声明中使用static。您需要使用typename
Regex
而不是变量
r

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

原因是在C#中,您无法通过该类型的实例访问
静态
方法。这里的
Replace
静态的
,因此必须通过类型
Regex
Ok来使用它,所以首先
default(Regex)
将简单地返回null,因为
Regex
是引用类型。因此,即使您的代码已编译,它也肯定会在这一行出现
NullReferenceException
崩溃,因为您从未向
r
分配任何有效的内容

DirtyString = r.Replace(DirtyString, "\\b" + element, "*****", RegexOptions.IgnoreCase);
接下来,编译器会准确地告诉您问题是什么
Replace
是一个静态方法,而不是实例方法,因此需要使用typename而不是实例变量

DirtyString = Regex.Replace(...);

阅读:,由创建此网站的人编写。什么是
Regex r=default(Regex)在代码中做什么?