c#替换字符串

本文关键字:字符串 替换 | 更新日期: 2023-09-27 18:08:10

我试图运行这段代码来替换字符串,但当我这样做时,它给了我一个错误,说

Error 1 A local variable named 'typeval' cannot be declared in this scope because it would give a different meaning to 'typeval', which is already used in a 'parent or current' scope to denote something else

代码

public static string Replace(string typeval)
{
    string newType = "";
    string typeval = "";
    if (typeval.Equals("User Service Request"))
    {
        newType = typeval.Replace("User Service Request", "incident");
    }
    else if (typeval.Equals("User Service Restoration"))
    {
        newType = typeval.Replace("User Service Restoration", "u_request");
    }
    return newType;
}

c#替换字符串

您已经定义了typeval once。你不能再次声明它。

删除string typeval == ""

您还应该将typval.Replace设置为typval而不是newType。否则,您将始终返回一个空字符串。

最后,您不需要if语句。您可以轻松地将函数简化为如下所示:

public static string Replace(string typeval)
{
    typeval = typeval.Replace("User Service Request", "incident");
    typeval = typeval.Replace("User Service Restoration", "u_request");
    return typeval;
}

有两种类型。一个在参数中,一个在函数中。重命名其中一个

您声明了一个与方法参数同名的局部变量。

有两个名为" typeval "的变量,因此会出现编译错误。