Problem with C # array "indexing cannot apply"

A potentially simple question here, I get an error: Cannot apply indexing with [] to an expression of type 'System.Array'

    public Array hello()
    {
        var damn = new[] { a2,a3,a4,a5,a6,a7,a8,a9};
        return damn;
    }
    private void a1disable()
    {

        var a = new[] { a1, a2, a3, a4, a5, a6, a7, a8, a9 };
        var b = hello();

        a[1].Enabled = false;
        b[1].Enabled = false;
    }

a[1].Enabled = false;works absolutely fine! it's just b[1].Enabled = false;that it throws the error described above, I haven't used many arrays before, so I'm sorry if the answer seems obvious, I'm just looking for clarification as to why this is happening. Thanks in advance if you can help :)

+4
source share
6 answers

All arrays come from Array, but are Arraynot indexed. Only concrete arrays are indexed. Without knowing the type of element that the array has, it is impossible to get the value from it in a strongly typed way.

Hello return a int[] .

+8

Array , GetValue, , b TextBox, :

((TextBox) b.GetValue(1)).Enabled = false;

, TextBox, TextBox[] hello()?

public TextBox[] hello(){
  //....
}
//Then you can keep the old code.
+4

Array - , , . Array :

Array , . Array. , .

whateverType[].

public whateverType[] hello()
{
    var damn = new[] { a2,a3,a4,a5,a6,a7,a8,a9};
    return damn;
}
+1

, , . :

    public List<object> hello()
    {
        return new List<object> { a2, a3, a4, a5, a6, a7, a8, a9 };
    }

"" . , / , , , . LINQ. .

0

, :

public Control[] hello()
{
    return new Control[] { a2,a3,a4,a5,a6,a7,a8,a9};
}

, Enabled.

, :

private Control[] _hello = new Control[] { a2,a3,a4,a5,a6,a7,a8,a9};

, , -:

public Control[] Hello {get; private set;}

    // init somewhere (to example, in the constructor)
    Hello = new Control[] { a2,a3,a4,a5,a6,a7,a8,a9};
0

If you cannot change the function that returns the type Array, hello () in your example and know the base type stored in the array, I use intin my example below. Then you can add using System.Linq;and change:

var b = hello();

to

var b = hello().Cast<int>().ToArray();
0
source

All Articles