0

我是 .NET MVC 的新手,来自 PHP/Java/ActionScript。

我遇到的问题是 .NET 模型和get{}. 我不明白为什么我的Hyphenize字符串会返回SomeText截断为 64 个字符的值,但不会替换数组中定义的任何字符。

模型 - 这应该SomeText用一个简单的连字符替换某些字符-

    public string SomeText{ get; set;} // Unmodified string

    public string Hyphenize{ 
        get {
            //unwanted characters to replace
            string[] replace_items = {"#", " ", "!", "?", "@", "*", ",", ".", "/", "'", @"\", "=" };
            string stringbuild = SomeText.Substring(0, (SomeText.Length > 64 ? 64 : SomeText.Length));

            for (int i = 0; i < replace_items.Length; i++)
            {
                stringbuild.Replace(replace_items[i], "-");
            }

            return stringbuild;
        }

        set { }
    }

或者,下面的方法确实可以正常工作,并将返回替换了" ""#"字符的字符串。但是,令我困扰的是,我无法理解为什么 for 循环不起作用。

    public string Hyphenize{ 
        get {
            //Replaces unwanted characters
            return SomeText.Substring(0, (SomeText.Length > 64 ? 64 : SomeText.Length)).Replace(" ", "-").Replace("#", "-");
        }

        set { }
    }

最终我结束了

return Regex.Replace(SomeText.Substring(0, (SomeText.Length > 64 ? 64 : SomeText.Length)).Replace("'", ""), @"[^a-zA-Z0-9]", "-").Replace("--", "-");
4

2 回答 2

8

string不可变的,来自MSDN

Strings are immutable--the contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this.

so you need to have to assign again:

 stringbuild = stringbuild.Replace(replace_items[i], "-");
于 2013-04-16T15:56:33.587 回答
2

You're not assigning the value of Replace() to anything. It returns its result, and does not modify the string that it operates on. (String's are immutable).

于 2013-04-16T15:57:22.337 回答