【发布时间】:2018-06-29 06:17:46
【问题描述】:
当我从 resx 声明一个 const 时,我遇到了编译错误。
private const string ERROR_MESSAGE = MyResource.ResourceManager.GetString("resx_key");
我明白为什么会出现此编译消息,但有什么技巧可以从资源中声明 const 吗?
【问题讨论】:
标签: c# resources constants resx
当我从 resx 声明一个 const 时,我遇到了编译错误。
private const string ERROR_MESSAGE = MyResource.ResourceManager.GetString("resx_key");
我明白为什么会出现此编译消息,但有什么技巧可以从资源中声明 const 吗?
【问题讨论】:
标签: c# resources constants resx
这是因为const 必须是编译时间常数。引用 MSDN 文档:
常量是不可变的值,在编译时是已知的,在程序的生命周期内不会改变。
来自https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/constants
在您的情况下,值来自方法调用。所以编译的时候可能不知道结果。原因是常量值直接替换到IL代码中。
事实上,当编译器在 C# 源代码中遇到常量标识符(例如,月份)时,它会将文字值直接替换为它生成的中间语言 (IL) 代码。
因此,您可以在这里使用static readonly,而不是const:
private static readonly string ERROR_MESSAGE = MyResource.ResourceManager.GetString("resx_key");
【讨论】: