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
提交
取消