[英]Converting from vb.net to c#, switch function not working
所以我一直在C#(老實說,我使用在線vb.net到c#轉換器)中的一個小項目(以前用vb.net構建)。到特定的預定名稱(硬編碼)。
首先是工作部分...
按下 button_1,打開一個文件對話框,你會看到 select 文件。 然后將它們填充到 listbox_1 中。
現在按下 button_2,listbox_1 中的文件被重命名並發送到 listbox_2。
現在我遇到的問題...
出於某種原因,我無法弄清楚,名稱沒有通過 switch 語句更改,它們只是獲取字符串變量名稱並用空白條目填充 listbox_2 (因為起始變量為空)。
string NewFileName = "";
我不確定這里發生了什么,所以如果有人能夠幫助我,那就太好了。
private string GetNewName(string OriginalFileName)
{
string NewFileName = "";
switch (true)
{
case object _ when OriginalFileName.Contains(".0001"):
{
NewFileName = OriginalFileName.Replace(".0001", "APPLE");
break;
}
case object _ when OriginalFileName.Contains(".0002"):
{
NewFileName = OriginalFileName.Replace(".0002", "PEAR");
break;
}
}
return NewFileName;
}
private void BTN_ProcessNames_Click(object sender, EventArgs e)
{
foreach (Tuple<string, string> t in listbox_1.Items)
{
var NewName = GetNewName(t.Item2);
listbox_2.Items.Add(NewName);
}
}
我會創建一個映射:
private static readonly IReadOnlyDictionary<string, string> _mapping = new Dictionary<string, string>()
{
{ "0001", "APPLE" },
{ "0002", "PEAR" }
};
然后是提取 id 的方法,在映射中查找並替換它:
private string GetNewName(string originalFileName)
{
// if the path is c:\test\Green_.0001.jpg then we'll end up with filePath containing c:\test and fileName containing Green_.0001.jpg
string filePath = Path.GetDirectoryName(originalFileName);
string fileName = Path.GetFileName(originalFileName); // get only the name part
// Split the filename by .
string[] parts = fileName.Split('.');
// If we have enough parts in the filename try and extract the id and replace it
if (parts.Length >= 2)
{
// extract the id (e.g. 0001)
string id = parts[parts.Length - 2];
// look it up in the mapping dictionary
if (_mapping.TryGetValue(id, out var newName))
{
// join everything up to the id (i.e. Green_)
string leftPart = string.Join(".", parts.Take(parts.Length - 2));
// Append the new name and the last part (the extension)
fileName = $"{leftPart}{newName}.{parts.Last()}";
}
}
// Recombine the filePath and fileName
return Path.Combine(filePath, fileName);
}
請注意,如果 id 不在映射中,或者文件名不包含足夠的.
s。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.