当我从resx声明一个const时,我有一个编译错误。
private const string ERROR_MESSAGE = MyResource.ResourceManager.GetString(“resx_key”);我理解为什么会出现这个编译消息……
那是因为a const 必须是编译时常量。引用MSDN文档:
const
常量是不可变的值,它们在编译时是已知的,并且在程序的生命周期内不会更改。 <子> 从 https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/constants 子>
常量是不可变的值,它们在编译时是已知的,并且在程序的生命周期内不会更改。
<子> 从 https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/constants 子>
在您的情况下,值来自方法调用。因此在编译时可能不知道结果。原因是常量值直接替换为IL代码。
实际上,当编译器在C#源代码中遇到常量标识符(例如,几个月)时,它会将文字值直接替换为它生成的中间语言(IL)代码。
而不是 const ,你可以用一个 static readonly 这里:
static readonly
private static readonly string ERROR_MESSAGE = MyResource.ResourceManager.GetString("resx_key");