[英]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.