如何解决“方法'Replace'的不重载采用'1'参数”

问题描述 投票:0回答:2

我想将包含“ Left”的字符串替换为“ Right”,旧代码只是将“ Left”替换为“ R”,我在网上寻找各种解决方案没有运气,并保持错误“方法没有重载' “替换”带有“ 1”个参数”,(我没有写这个)这是代码示例:

 public void FlipLRXsp()
    {
        if (this.parentSurvey.SectionEditing != true)
        {
            throw new Exception("Trying to flip XSP outside section editing.");
        }

        bool changed = false;

        foreach (NvoItem item in this.ItemList)
        {
            string xsp = item.Xsp.ToUpper();
            if (xsp.Contains("Left") == true)
            {
                # old code item.Xsp = xsp.Replace('R', 'L');
                # new code item.Xsp = xsp.Replace("Right");
                changed = true;
            }
            else if (xsp.Contains("Right") == true)
            {
                item.Xsp = xsp.Replace('L', 'R');
                changed = true;
            }
        }

        if (changed == true) this.IsModified = true;
    }
c#
2个回答
0
投票

因为这行代码

item.Xsp = xsp.Replace("Right");

您需要告诉方法将哪个(第一参数)替换为什么(第二参数)。尝试使用此代码,它将所有“左”事件替换为“右”。

item.Xsp = xsp.Replace("Left", "Right");

0
投票

您的代码中存在多个错误。请仔细阅读以下代码中的注释。还要确定您是否真的需要使用.ToUpper()

    public void FlipLRXsp()
    {
        if (this.parentSurvey.SectionEditing != true)
        {
            throw new Exception("Trying to flip XSP outside section editing.");
        }

        bool changed = false;

        foreach (NvoItem item in this.ItemList)
        {
            string xsp = item.Xsp.ToUpper();
            // ToUpper converts all letters to capital, so compare with 'LEFT'
            if (xsp.Contains("LEFT")) // .Contains return boolean value, so comparison with 'true' is not needed
            {
                # old code item.Xsp = xsp.Replace('R', 'L'); // this replaces only single character
                # new code item.Xsp = xsp.Replace("Right");
                item.Xsp = xsp.Replace("LEFT", "RIGHT"); // replace LEFT with RIGHT
                changed = true;
            }
            else if (xsp.Contains("RIGHT"))
            {
                item.Xsp = xsp.Replace('RIGHT', 'LEFT'); // replace RIGHT with LEFT
                changed = true;
            }
        }

        if (changed) 
            this.IsModified = true;
    }
© www.soinside.com 2019 - 2024. All rights reserved.