接收'赋值表达式必须为常量'当它是

本文关键字:常量 赋值 表达式 接收 | 更新日期: 2023-09-27 18:08:03

有没有办法使用这样的东西:

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

我认为这样做会比使用

更具可读性,更不容易出错:
private const int MaxTextLength = 18;

是否有任何方法可以将文本的长度作为常量变量的来源?

接收'赋值表达式必须为常量'当它是

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

static readonly代替const

常量必须是编译时常量

不幸的是,如果使用const关键字,'='右侧的值必须是编译时常数。使用"字符串"。长度要求. net代码只能在应用程序运行时执行,而不是在编译时执行。

可以考虑将字段设置为只读而不是const。

该值必须为const吗?静态只读是否适合您的情况?

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

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

不知道为什么要这样做,但是如何…

private const string MaxText = "Text i want to use.";
private static int MaxTextLength { get { return MaxText.Length; } }