为什么我不能在数组C#中声明字符串

时间:2016-05-02 22:22:30

标签: c# arrays string visual-studio

我正在尝试制作一个充满电视节目名称的C#课程。当我检查正确的方式在线做一个Srting阵列时,似乎我做得对。我正在使用Visual Studio 2015.当我将鼠标悬停在String名称上时,它会显示“当前上下文中不存在DoctorEp的名称”当我将鼠标悬停在该数字上时,它表示“无法在变量声明中指定数组大小。 “这是我的代码片段,应该得到我的观点:

Class Names{
String[] DoctorEp = new String[107];
DoctorEp[0] = "rose";
DoctorEp[1] = "the end of the world";
DoctorEp[2] = "the unquiet dead";
DoctorEp[3] = "aliens of london";
DoctorEp[4] = "world war three";
DoctorEp[5] = "dalek";
DoctorEp[6] = "the long game";
DoctorEp[7] = "father's day";
DoctorEp[8] = "the empty child";
DoctorEp[9] = "the doctor dances";
DoctorEp[10] = "boom town";
}

5 个答案:

答案 0 :(得分:7)

您不能将语句放在函数之外。

相反,请使用数组初始值设定项:

String[] DoctorEp = { "rose", ... };

答案 1 :(得分:1)

您不能在方法外使用实例变量,这不是有效的:

class Names
{
    string var1 = "abc";
    string var2 = var1;
}

原因是无法保证编译器会按顺序保留这些内容,因此在您的情况下,您可以执行以下操作:

class Names
{
    String[] DoctorEp = new String[]
        {
            "rose",
            "the end of the world",
            "the unquiet dead",
            "aliens of london",
            "world war three",
            "dalek",
            "the long game",
            "father's day",
            "the empty child",
            "the doctor dances",
            "boom town",
        };
}

或:

class Names
{
    String[] DoctorEp = new String[107];

    public Names()
    {
        InitializeArray();
    }

    void InitializeArray()
    {
        DoctorEp[0] = "rose";
        DoctorEp[1] = "the end of the world";
        DoctorEp[2] = "the unquiet dead";
        DoctorEp[3] = "aliens of london";
        DoctorEp[4] = "world war three";
        DoctorEp[5] = "dalek";
        DoctorEp[6] = "the long game";
        DoctorEp[7] = "father's day";
        DoctorEp[8] = "the empty child";
        DoctorEp[9] = "the doctor dances";
        DoctorEp[1] = "boom town";
    }
}

答案 2 :(得分:0)

示例是否在类或函数中显示了这些确切的代码?

您已经使用变量创建了一个类,但是尝试通过在任何类方法之外设置字符串来处理变量(基本上是@SLaks提到的method = function)。您需要通过@SLaks或类构造函数或方法(如果不在类中的函数)中提到的数组初始化程序设置值,如下所示(使用类构造函数显示):

class Names {

    string[] DoctorEp = new string[11];

    public Names()
    {
        DoctorEp[0] = "rose";
        DoctorEp[1] = "the end of the world";
        DoctorEp[2] = "the unquiet dead";
        DoctorEp[3] = "aliens of london";
        DoctorEp[4] = "world war three";
        DoctorEp[5] = "dalek";
        DoctorEp[6] = "the long game";
        DoctorEp[7] = "father's day";
        DoctorEp[8] = "the empty child";
        DoctorEp[9] = "the doctor dances";
        DoctorEp[10] = "boom town";
    }
}

答案 3 :(得分:0)

好的,现在我明白了。我不能在课堂上放这样的声明。这是我的代码。它运作得很好。

Host:

答案 4 :(得分:-1)

使用linq

String[] DoctorEp = { "rose", ... }
    .Concat(Enumerable.Repeat<string>(null, 96))
    .ToArray();