嘗試獲取數組的索引時出錯

[英]Error when trying to get index of an Array


I have a program where the user inputs a string. This strings length is always a multiple of 8.

我有一個用戶輸入字符串的程序。此字符串長度始終是8的倍數。

So to convert the string I split the string every 8 characters into an array.

因此,為了轉換字符串,我將每8個字符的字符串拆分為一個數組。

I do that with this code

我用這段代碼做到了

Dim substrings = Enumerable.Range(0, input.Length \ 8).[Select](Function(i) input.Substring(i * 8, 8))

That works fine.

這很好。

I can then type String.Join(" ", substrings) and it works like it should, it takes whatever the user entered and puts a space between every 8 characters.

然后我可以鍵入String.Join(“”,substrings),它就像它應該的那樣工作,它接受用戶輸入的任何內容並在每8個字符之間放置一個空格。

However, if I try to do this:

但是,如果我嘗試這樣做:

Dim indexOfEntry
For Each e In substrings
    indexOfEntry = Array.IndexOf(substrings, e)
Next

I get an error:

我收到一個錯誤:

An unhandled exception of type 'System.InvalidCastException' occurred in DataCalculator.exe

Additional information: Unable to cast object of type 'WhereSelectEnumerableIterator`2[System.Int32,System.String]' to type 'System.Array'.

How can I fix this?

我怎樣才能解決這個問題?

2 个解决方案

#1


1  

Change the splitting line to return an array of strings

更改拆分線以返回字符串數組

 Dim substrings = Enumerable.Range(0, input.Length \ 8).[Select](Function(i) _ 
                                   input.Substring(i * 8, 8)).ToArray()

I really advice you to turn ON the OPTION STRICT flag in your VB.NET configuration.
This allows the compiler to examine your code for potential pitfalls like this.

我真的建議你打開VB.NET配置中的OPTION STRICT標志。這允許編譯器檢查代碼是否存在這樣的潛在缺陷。

The automatic conversions of values like it was in the VB6 time should not have a place in NET world (but this is an opinion and I reckon that porting of old programs is easier with that flag set to OFF.)

類似於VB6時間的值的自動轉換不應該在.NET世界中占有一席之地(但這是一個意見,我認為在將該標志設置為OFF時,更容易移植舊程序。)

#2


0  

Your substrings variable isn't an Array; it's an IEnumerable(Of String). You could convert it to an array with substrings.ToArray().

您的子串變量不是數組;它是一個IEnumerable(Of String)。您可以使用substrings.ToArray()將其轉換為數組。

Turning Option Strict On will catch errors like this at compile-time. In this case, you would see an "Overload resolution failed..." on the Array.IndexOf call, which would hint that the variable is not an array variable.

選項Strict On將在編譯時捕獲這樣的錯誤。在這種情況下,您會在Array.IndexOf調用中看到“Overload resolution failed ...”,這將暗示該變量不是數組變量。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2014/07/29/724d786cbee1f4c28e63c19e96eb6b97.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com