是否可以写出类似于下面的内容?
public const string[] Titles = { "German", "Spanish", "Corrects", "Wrongs" };
是否可以写出类似于下面的内容?
public const string[] Titles = { "German", "Spanish", "Corrects", "Wrongs" };
当前回答
这是一种做你想做的事情的方法:
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 string[] Titles
{
get
{
return new string[] { "German", "Spanish", "Corrects", "Wrongs"};
}
}
当然,这不是特别有效,因为每次都会创建一个新的字符串数组。
你可以采用一种不同的方法:定义一个常量字符串来表示你的数组,然后在你需要它的时候把字符串分割成一个数组。
const string DefaultDistances = "5,10,15,20,25,30,40,50";
public static readonly string[] distances = DefaultDistances.Split(',');
这种方法为您提供了一个可以存储在配置中并在需要时转换为数组的常量。
我相信你只能让它只读。
数组可能是一种只能在这里求值的东西 运行时。常量必须在编译时求值。尝试使用"readonly" 而不是"const"。
这是一种做你想做的事情的方法:
using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
public ReadOnlyCollection<string> Titles { get { return new List<string> { "German", "Spanish", "Corrects", "Wrongs" }.AsReadOnly();}}
它非常类似于做一个只读数组。