是否可以写出类似于下面的内容?

public const string[] Titles = { "German", "Spanish", "Corrects", "Wrongs" };

当前回答

你不能创建一个“const”数组,因为数组是对象,只能是对象 在运行时创建,const实体在编译时解析。

你可以将数组声明为“readonly”。这是 与const的效果相同,只是该值可以在运行时设置。它只能是 设置一次,之后它就是一个只读(即const)值。

其他回答

为了我的需要,我定义了静态数组,而不是不可能的const,它工作: 公共静态字符串[]title ={"德语","西班牙语","纠正","错误"};

这是一种做你想做的事情的方法:

using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;

public ReadOnlyCollection<string> Titles { get { return new List<string> { "German", "Spanish", "Corrects", "Wrongs" }.AsReadOnly();}}

它非常类似于做一个只读数组。

最好的选择:

public static readonly byte[] ZeroHash = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

作为一种替代方法,要解决使用只读数组可以修改元素的问题,可以使用静态属性。(单个元素仍然可以更改,但这些更改只会在数组的本地副本上进行。)

public static string[] Titles 
{
    get
    {
        return new string[] { "German", "Spanish", "Corrects", "Wrongs"};
    }
}

当然,这不是特别有效,因为每次都会创建一个新的字符串数组。

我相信你只能让它只读。