static void Main(string[] args){string str1 = Console.ReadLine();string str2 = "";byte[] byt=new byte[100];byt = Encoding.Unicode.GetBytes(str1);str2 = Encoding.Unicode.GetString(byt).Substring (0,byt.Length );Console.Write(str2);Console.ReadLine();}这里出现未处理 System.ArgumentOutOfRangeExceptionMessage="索引和长度必须引用该字符串内的位置。\r\n参数名: length"Source="mscorlib"ParamName="length"StackTrace:在 System.String.InternalSubStringWithChecks(Int32 startIndex, Int32 length, Boolean fAlwaysCopy)在 System.String.Substring(Int32 startIndex, Int32 length)在 ConsoleApplication15.Program.Main(String[] args) 位置 E:\chen\Visual Studio 2008\Projects\文件\ConsoleApplication15\ConsoleApplication15\Program.cs:行号 17在 System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)在 System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)在 Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()在 System.Threading.ThreadHelper.ThreadStart_Context(Object state)在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)在 System.Threading.ThreadHelper.ThreadStart()InnerException:请问是怎么回事?
2 回答
倚天杖
TA贡献1828条经验 获得超3个赞
string str1 = "dsfadfasdfasdfasdfasdfasdfasdfasdf";
string str2 = "";
byte[] byt = new byte[100];
byt = Encoding.Unicode.GetBytes(str1);
str2 = Encoding.Unicode.GetString(byt).Substring(0, byt.Length);
Console.Write(str2);
Console.ReadLine();
上边是我假设的,此时假设 str1为 "dsfadfasdfasdfasdfasdfasdfasdfasdf"
虽然你定义了 byte[] byt = new byte[100];
但是GetBytes在生成字节序列的时候,填充了数组的前68个,后边的都是空的,
这样解码为str2的时候他的dsfadfasdfasdfasdfasdfasdfasdfasdf的长度还是原来的长度,但是你的byt.Length是100,这样就造成了越界了,肯定会报错的 ,
建议你数组可以使用arraylist可变长数组,
添加回答
举报
0/150
提交
取消