是否可以写出类似于下面的内容?
public const string[] Titles = { "German", "Spanish", "Corrects", "Wrongs" };
是否可以写出类似于下面的内容?
public const string[] Titles = { "German", "Spanish", "Corrects", "Wrongs" };
当前回答
如果你在IReadOnlyList接口后面声明了一个数组,你会得到一个常量数组,在运行时声明常量值:
public readonly IReadOnlyList<string> Titles = new [] {"German", "Spanish", "Corrects", "Wrongs" };
在. net 4.5及更高版本中可用。
其他回答
这是一种做你想做的事情的方法:
using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
public ReadOnlyCollection<string> Titles { get { return new List<string> { "German", "Spanish", "Corrects", "Wrongs" }.AsReadOnly();}}
它非常类似于做一个只读数组。
是的,但是你需要声明它为readonly而不是const:
public static readonly string[] Titles = { "German", "Spanish", "Corrects", "Wrongs" };
原因是const只能应用于编译时已知值的字段。您所展示的数组初始化器不是c#中的常量表达式,因此会产生编译器错误。
声明它为readonly可以解决这个问题,因为值直到运行时才初始化(尽管可以保证在第一次使用数组之前已经初始化)。
根据你最终想要实现的目标,你也可以考虑声明一个枚举:
public enum Titles { German, Spanish, Corrects, Wrongs };
快速的解决方法,说不定对别人有帮助。我需要一个字符串[]作为Attribute的参数(在某些理论中为测试用例传递内联数据)。Readonly在这里没用。但是,我最后做的是:
const string foo = "a|b|c";
[InlineData(foo)]
public void Test(string fooString)
{
var foo = fooString.Split("|"); // foo == {"a","b","c"}
...
}
你不能创建一个“const”数组,因为数组是对象,只能是对象 在运行时创建,const实体在编译时解析。
你可以将数组声明为“readonly”。这是 与const的效果相同,只是该值可以在运行时设置。它只能是 设置一次,之后它就是一个只读(即const)值。
数组可能是一种只能在这里求值的东西 运行时。常量必须在编译时求值。尝试使用"readonly" 而不是"const"。