C#返回值调用循环中的变量
本文关键字:变量 循环 值调用 返回 返回值 | 更新日期: 2023-09-27 18:29:36
这是文本文件
country1: 93#country2: 355#country3: 213#country4: 376#country5: 244#country6: 54#country7: 374#
对于这个ASP.NET web服务,当我声明字符串temp ouside"For"循环时,错误"使用未分配的本地变量‘temp’"
[webMethod]
public string[] getContryCode ()
{
string temp;
string[] data = File.ReadAllLines(@"countryCode.txt");
string[] country = data[0].Split('#');
for (int i = 0; i < country.Length; i++ )
{
temp = country[i];
}
//const string f = "countryCode.txt";
return temp.Split(':');
}
如果我在循环中声明字符串temp,我不能返回"temp.Split(':')"的值。需要找到一种方法来解决
原始文件格式:#country1:code1#country2:code2#
数组列表'country':[0] country1 code1 country2 code2
-i可以获得此工作b拆分temp.split(":"):应该得到这样的[0]country1 [1] code1 [2] country2 [3] code2
你的for循环不能保证迭代一次,所以当你尝试使用它时,你会得到一个编译器错误,temp可能没有值。
尝试:
string temp = "";
不过,更好的做法是添加适当的测试,以确保您的所有输入都如预期:
if ( !System.IO.File.Exists( @"countryCode.txt" ) )
throw new ApplicationException( "countryCode.txt is missing" );
string[] data = File.ReadAllLines(@"countryCode.txt");
if ( data.Length == 0 )
throw new ApplicationException( "countryCode.txt contains no data" );
if ( data[0].Length == 0 )
throw new ApplicationException( "malformed data in countryCode.txt" );
string[] country = data[0].Split('#');
string temp = "";
for (int i = 0; i < country.Length; i++ )
{
temp = country[i];
}
return temp.Split(':');
不过,我真的不确定你想用for循环完成什么,因为你只会返回country数组中的最后一个项目,它与:return country[country.Length - 1];
相同
编辑:
您可能需要删除country
数组中的空条目。您只需使用RemoveEmptyEntries选项:
string[] country = data[0].Split('#', StringSplitOptions.RemoveEmptyEntries);
/* Using the RemoveEmptyEntries option can cause the function to
return a 0-length array, so need to check for that afterall: */
if ( country.Length == 0 )
throw new ApplicationException( "malformed data in countryCode.txt" );