从资源中声明一个 const 字符串

Declare a const string from a resource

当我从 resx 声明 const 时出现编译错误。

private const string ERROR_MESSAGE = MyResource.ResourceManager.GetString("resx_key");

我明白为什么会出现此编译消息,但是是否有从资源声明 const 的技巧?

那是因为 const 必须是一个编译时常量。引用 MSDN 文档:

Constants are immutable values which are known at compile time and do not change for the life of the program.

From https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/constants

在您的情况下,该值来自方法调用。所以编译的时候可能还不知道结果。这样做的原因是常量值被直接代入了IL代码。

In fact, when the compiler encounters a constant identifier in C# source code (for example, months), it substitutes the literal value directly into the intermediate language (IL) code that it produces.

因此,您可以在此处使用 static readonly 而不是 const

private static readonly string ERROR_MESSAGE = MyResource.ResourceManager.GetString("resx_key");