2011-09-08 42 views
18

有没有使用这样的方式:接收“的表达被分配必须是常量”当它是

private const int MaxTextLength = "Text i want to use".Length; 

我认为这将是更具可读性和误差比使用类似易少:

private const int MaxTextLength = 18; 

有什么方法有文本的长度是一个常数变量的来源?

+9

“常数变量”? – BoltClock

回答

23
private readonly static int MaxTextLength = "Text i want to use".Length; 
12

使用static readonly代替const

常数必须编译时间常数

+1

但静态只读变量在case语句中不起作用。 – MSTdev

5

不幸的是,如果你使用const关键字在“=”必须是一个编译时间常数的右边的值。使用“字符串”.length需要.NET代码执行,只能在应用程序运行时才执行,而不是在编译期间执行。

你可以考虑做现场只读,而不是一个常量。

0

不知道为什么你想这样做,但怎么样......

private const string MaxText = "Text i want to use."; 

private static int MaxTextLength { get { return MaxText.Length; } } 
0

是否值必须是一个const?静态只读是否适合你的情况?

private static readonly int MaxTextLength = "Text i want to use".Length; 

这将允许您以类似于第一个示例的方式编写代码。

相关问题