Tan*_*ank 0 c# variables asp.net-mvc
我是.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 { }
}
Run Code Online (Sandbox Code Playgroud)
或者,下面的方法可以正常工作,并将返回字符串" "和"#"替换字符.然而,令我困扰的是,我无法理解为什么for循环不起作用.
public string Hyphenize{
get {
//Replaces unwanted characters
return SomeText.Substring(0, (SomeText.Length > 64 ? 64 : SomeText.Length)).Replace(" ", "-").Replace("#", "-");
}
set { }
}
Run Code Online (Sandbox Code Playgroud)
最终我最终得到了
return Regex.Replace(SomeText.Substring(0, (SomeText.Length > 64 ? 64 : SomeText.Length)).Replace("'", ""), @"[^a-zA-Z0-9]", "-").Replace("--", "-");
Run Code Online (Sandbox Code Playgroud)
string来自MSDN的是不可变的:
字符串是不可变的 - 在创建对象后,字符串对象的内容无法更改,尽管语法使其看起来好像可以执行此操作.
所以你需要再次分配:
stringbuild = stringbuild.Replace(replace_items[i], "-");
Run Code Online (Sandbox Code Playgroud)