【问题标题】:C# replace stringC# 替换字符串
【发布时间】:2013-04-01 03:09:43
【问题描述】:

我正在尝试运行此代码来替换一个字符串,但是当我这样做时,它给了我一个错误提示

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

【问题讨论】:

  • 而且这个错误信息还不足以提示你也许应该尝试重命名两个typevals 之一?
  • 为变量 typeval 赋予不同的名称。错误是您已经在父级中使用了具有此名称的变量。只需更改此变量的名称即可解决您的问题
  • 建议您以后搜索此类错误。

标签: c# string replace return


【解决方案1】:

您已经定义了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;
}

【讨论】:

  • 如果我发送用户服务请求或用户服务恢复,我得到一个 u_request 的返回,它看起来不像它的工作
  • @Deanvd 你试过我发布的完整代码了吗?您应该删除 newType 并将其替换为 typeval,例如typeval = typeval.Replace("User Service Request", "incident"); 然后返回typeval,而不是newType
  • 上面用Console.WriteLine(Replace("User Service Request 5 -- User Service Restoration 6"));执行的代码返回incident 5 -- u_request 6
  • @eandersson - 我试着像下面一样“编码”你的代码:( public static string Replace(string typeval) { typeval = typeval.Replace("User Service Request", "incident"); typeval = typeval.Replace("用户服务恢复", "u_request"); return typeval; }
  • @eandersson 我得到了想要的结果(通过视觉工作室),但现在必须将它作为内联 c# 添加到 BizTalk 中然后我不明白:(
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    您正在声明一个与方法参数同名的本地变量。

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        猜你喜欢
        • 2010-12-06
        • 2013-05-26
        • 2011-10-20
        • 2014-04-11
        • 2014-07-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多