String.Replace C#.NET

Fab*_*pet 1 .net c# replace

我想知道它为什么不起作用

string filename = optionFileNameFormat; // "{year}-{month}-{day} {name}"
Dictionary<string, string> tagList = new Dictionary<string, string>();
tagList.Add("author",System.Security.Principal.WindowsIdentity.GetCurrent().Name);
tagList.Add("year" , "" + DateTime.Now.Year);
tagList.Add("month", "" + DateTime.Now.Month);
tagList.Add("day"  , "" + DateTime.Now.Day);

foreach (var property in tagList)
{
    filename.Replace(@"{" + property.Key + @"}", property.Value);
}
Run Code Online (Sandbox Code Playgroud)

我没有任何错误,但我的字符串没有改变.谢谢

Joe*_*orn 12

可能还有其他问题,但是马上跳出来的是该Replace()函数不会改变字符串.相反,它返回一个新字符串.因此,您需要将函数的结果分配回原始函数:

filename = filename.Replace(@"{" + property.Key + @"}", property.Value);
Run Code Online (Sandbox Code Playgroud)

  • 详细说明:这是因为字符串是不可变的,所以如果你*曾经*调用一个方法来改变一个,实际发生的是该方法返回改变的字符串并且原始字符串是未修改的. (2认同)