Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/262.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# string.Substring命令不工作_C#_String_String Comparison - Fatal编程技术网

C# string.Substring命令不工作

C# string.Substring命令不工作,c#,string,string-comparison,C#,String,String Comparison,我有一个带有打印机列表的下拉列表,我想从drowdownlist.SelectedItem.Text中获取前三位数字,原因是我需要计算项目的旋转代码 代码如下: string[] plantname = Printerlist.SelectedItem.Text.Split('-'); string plantvalue = plantname[0].ToString(); if (plantvalue.Substring(0,3).ToLower() == "abk"){

我有一个带有打印机列表的下拉列表,我想从
drowdownlist.SelectedItem.Text
中获取前三位数字,原因是我需要计算项目的旋转代码

代码如下:

string[] plantname = Printerlist.SelectedItem.Text.Split('-');
string plantvalue = plantname[0].ToString();
if (plantvalue.Substring(0,3).ToLower() == "abk"){
   rotation_plant = "9";
 }
 else if (plantvalue.Substring(0, 3).ToLower() == "cor")
 {
    rotation_plant = "3";
 }
 else if (plantvalue.Substring(0, 3).ToLower() == "iok")
 {
    rotation_plant = "0";
 }
 else if (plantvalue.Substring(0, 3).ToLower() == "moc")
 {
    rotation_plant = "6";
 }
 else if (plantvalue.Substring(0, 3).ToLower() == "tes")
 {
    rotation_plant = "1";
 }
在调试中,我看到plantvalue:

但上述子串必须等于“tes”,但:

我进行了一次重建,我关闭了应用程序并重新打开了它,但它仍然不工作,是否有人面临类似的问题如果是这样,您是如何解决的请帮助……

在您的情况下,Substring方法返回一个新字符串,其中包含索引0到2的图表

在调试器中,仍然检查plantvalue变量,而不是Substring方法的结果。 尝试将子字符串放入新变量中,即:

string lowerThreeLetters = plantvalue.Substring(0, 3).ToLower();

这样,通过将鼠标悬停在lowerThreeLetters变量上,您将能够在debug中看到3个第一个字母,并且只对子字符串进行一次计算,而不是对每个if语句进行计算。

Quick suggestion-我将拉动
plantvalue.Substring(0,3).ToLower()
转换为它自己的变量,以便更容易理解和调试。除此之外,它还会触发我的性能OCD。为什么要重复
子字符串
ToLower
操作?@BrianRasmussen是的,性能是一回事,但使用
开关(plantvalue.Substring(0,3.ToLower()){case“abk”:/*…*/}
,代码可能更简单易读。@BrianRasmussen也许roslyn无法理解,但这些都是纯函数,因此理论上它们可以被缓存。无论如何,它们都是调用如此小的字符串的廉价方法,因此您应该更加关注代码的重复和可读性的恶化。我们可以问一下,什么是数值
(ushort)plantvalue[0]
,什么是
(ushort)plantvalue[1]
,什么是
(ushort)plantvalue[2]
,什么是
CultureInfo.CurrentCulture
?什么是
(ushort)plantvalue.Substring(0,3)[0]
等等?可能字符串包含“不可见”字符或其他意外的UTF-16代码单元。