IndexOf 在 c# 中没有 return 任何值
IndexOf does not return any value in c#
这似乎是一个重复的问题,但事实并非如此。
我有一个简单的代码。有一个名为 book
的字符串,其值为 "mybook"
。
我想在 "mybook"
字符串中找到 'y'
字符的索引。所以我使用了这段代码,但它没有 return 'y'
字符的索引。
string book = "mybook";
char y = 'y';
int yPosition = book.IndexOf(y);
Console.WriteLine("y position is: ", yPosition);
当我运行这段代码时,答案是这样的,仅此而已:
y position is:
您忘记打印 yPosition 的值:
Console.WriteLine($"y position is: {yPosition}");
IndexOf 方法 returns -1 如果在此实例中未找到字符或字符串。这就是为什么你的变量 yPosition
应该总是有一些 int 值。如果你在该行设置断点,你可以检查它:
int yPosition = book.IndexOf(y);
您忘记了格式化元素将包含在您的格式字符串中的位置。
如果你改变
Console.WriteLine("y position is: ",yPosition);
到
Console.WriteLine("y position is: {0}",yPosition);
你应该得到想要的行为。如果您要在 Console.WriteLine
调用上放置一个断点,您可以在调试模式下验证 yPosition
有一个值,并且它的值为 1.
在 Console.WriteLine
中,您忘记为 yPosition
提供格式位置。将行更改为以下内容:
Console.WriteLine("y position is: {0}",yPosition);
这似乎是一个重复的问题,但事实并非如此。
我有一个简单的代码。有一个名为 book
的字符串,其值为 "mybook"
。
我想在 "mybook"
字符串中找到 'y'
字符的索引。所以我使用了这段代码,但它没有 return 'y'
字符的索引。
string book = "mybook";
char y = 'y';
int yPosition = book.IndexOf(y);
Console.WriteLine("y position is: ", yPosition);
当我运行这段代码时,答案是这样的,仅此而已:
y position is:
您忘记打印 yPosition 的值:
Console.WriteLine($"y position is: {yPosition}");
IndexOf 方法 returns -1 如果在此实例中未找到字符或字符串。这就是为什么你的变量 yPosition
应该总是有一些 int 值。如果你在该行设置断点,你可以检查它:
int yPosition = book.IndexOf(y);
您忘记了格式化元素将包含在您的格式字符串中的位置。
如果你改变
Console.WriteLine("y position is: ",yPosition);
到
Console.WriteLine("y position is: {0}",yPosition);
你应该得到想要的行为。如果您要在 Console.WriteLine
调用上放置一个断点,您可以在调试模式下验证 yPosition
有一个值,并且它的值为 1.
在 Console.WriteLine
中,您忘记为 yPosition
提供格式位置。将行更改为以下内容:
Console.WriteLine("y position is: {0}",yPosition);