ato*_*eki 0 c# variables for-loop return
这是文本文件
country1: 93#country2: 355#country3: 213#country4: 376#country5: 244#country6: 54#country7: 374#
Run Code Online (Sandbox Code Playgroud)
对于这个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(':');
}
Run Code Online (Sandbox Code Playgroud)
如果我在循环中声明字符串temp,我不能返回值"temp.Split(':')".需要找到解决它的方法
originl文件格式:#country1:code1#country2:code2#
数组列表'country':[0] country1 code1 country2 code2- 我可以得到这个工作b split temp.split(':'):应该得到这样的东西[0]country1 [1] code1 [2] country2 [3] code2
您的for循环不保证迭代一次,因此当您尝试使用它时,您将收到一个编译器错误,即temp可能没有值.
尝试:
string temp = "";
Run Code Online (Sandbox Code Playgroud)
但更好的方法是添加适当的测试以确保所有输入都符合预期:
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(':');
Run Code Online (Sandbox Code Playgroud)
我不确定你要用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" );
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
318 次 |
| 最近记录: |