簡體   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