Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 数组问题c“;无法应用索引";_C#_Arrays - Fatal编程技术网

C# 数组问题c“;无法应用索引";

C# 数组问题c“;无法应用索引";,c#,arrays,C#,Arrays,这里有一个可能很简单的问题,我得到了一个错误:无法将带[]的索引应用于'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

这里有一个可能很简单的问题,我得到了一个错误:
无法将带[]的索引应用于'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工作非常好!它只是
b[1]。Enabled=false
抛出了我上面描述的错误,我以前很少使用数组,所以如果答案看起来很明显,我很抱歉,我只是想澄清一下为什么会发生这种情况。
如果您能提供帮助,请提前感谢:)

Array
类没有任何索引器,您必须使用
GetValue
方法,假设
b
中每个元素的类型为
TextBox
,请尝试以下操作:

((TextBox) b.GetValue(1)).Enabled = false;
如果您事先知道所有元素的类型,例如
TextBox
,为什么不使用type
TextBox[]
作为
hello()
方法的返回类型呢

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

所有数组都派生自
数组
,但
数组
不可索引。只有混凝土阵列是可转位的。如果不知道数组的元素类型,就不可能以强类型的方式从中获取值


使
Hello
返回
int[]
或任何正确的元素类型。

通过返回泛型而不是数组,可以使语法更简单。在您的情况下,这看起来像:

    public List<object> hello()
    {
        return new List<object> { a2, a3, a4, a5, a6, a7, a8, a9 };
    }
公共列表hello()
{
返回新列表{a2、a3、a4、a5、a6、a7、a8、a9};
}

只需用适当的类型替换“object”。它们的优点是,如果需要,您可以在以后添加/删除项,这比使用数组更容易。它们还扩展了对LINQ语法的支持。只是一个建议。

数组主要是系统的基类。您将使用
Array
作为返回:

Array类是用于以下语言实现的基类: 支持阵列。但是,只有系统和编译器才能派生 显式地从数组类中删除用户应使用该阵列 语言提供的构造。

将返回类型更改为
whateverType[]

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

如果使用控件,则可以执行以下操作:

public Control[] hello()
{
    return new Control[] { a2,a3,a4,a5,a6,a7,a8,a9};
}
通过这种方式,您可以访问所需的控件属性,如
已启用

我认为将其简化为一个私人领域更好:

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};

如果您无法修改示例中返回类型为
Array
、hello()的函数,并且知道数组中存储的基类型,我将在下面的示例中使用
int
。然后可以使用System.Linq添加
和更改:

var b = hello();

var b=hello().Cast().ToArray();

a1、a2等实际上是文本框,这是否意味着我可以/应该将“按钮”更改为“文本框”?@LucasHolmes不,只是将
Button
替换为
Textbox
,这只是我的假设。我很惊讶
hello()
方法在将某个类[]强制转换为数组时会编译。投票给一个我不知道的问题。
var b = hello().Cast<int>().ToArray();