从 vb.net 转换为 C#,切换功能不起作用

Converting from vb.net to c#, switch function not working

所以我一直在用 C# 开发一个小项目(以前用 vb.net 构建)(老实说,我使用在线 vb.net 到 c# 转换器来达到这一点。)这基本上会将一组文件的后缀重命名为特定的预定名称(硬编码)。

首先是工作部分...

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

使用 if else 语句。如果你想使用switch,那么先检查一下,然后再使用switch。

使用下面link作为参考。

Use string.Contains() with switch()

我会创建一个映射:

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,此方法将 return 原始文件名。

Try it online