繁体   English   中英

C# .NET 中的 String.Replace

[英]String.Replace in C# .NET

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

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

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

可能还有其他问题,但让我立即想到的是Replace()函数不会更改 string 相反,它返回一个新字符串。 因此,您需要将函数的结果赋值回原来的:

filename = filename.Replace(@"{" + property.Key + @"}", property.Value);

String.Replace方法返回一个新字符串。 它不会改变原始字符串。

返回一个新字符串,其中当前字符串中所有出现的指定 Unicode 字符或字符串都被另一个指定的 Unicode 字符或字符串替换

因此,您应该在foreach循环中分配一个新字符串或现有字符串:

filename = filename.Replace(@"{" + property.Key + @"}", property.Value);

要么

string newfilename = filename.Replace(@"{" + property.Key + @"}", property.Value);

请记住,在 .NET 中,字符串是不可变类型 你不能改变它们。 即使您认为您更改了它们,您也会创建新的字符串对象。

foreach (var property in tagList)
{
    filename.Replace(@"{" + property.Key + @"}", property.Value);
}

只需进行以下更改:

filename =  filename.Replace(@"{" + property.Key + @"}", property.Value);

这是完成的代码:

 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= filename.Replace(@"{" + property.Key + @"}", property.Value);
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM