Declare a const string from a resource

G.D*_*ida 4 c# resources resx constants

When I declare a const from a resx I have a compilation error.

private const string ERROR_MESSAGE = MyResource.ResourceManager.GetString("resx_key");
Run Code Online (Sandbox Code Playgroud)

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

Nis*_*arg 5

这是因为 aconst必须是编译时常量。引用MSDN文档:

常量是不可变的值,在编译时已知,并且在程序的生命周期内不会改变。

来自https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/constants

在您的情况下,该值来自方法调用。所以编译时可能不知道结果。原因是常量值被直接替换到IL代码中。

事实上,当编译器在 C# 源代码中遇到常量标识符(例如,月份)时,它会将文字值直接替换为它生成的中间语言 (IL) 代码。

因此const,您可以在此处使用 a来代替static readonly

private static readonly string ERROR_MESSAGE = MyResource.ResourceManager.GetString("resx_key");
Run Code Online (Sandbox Code Playgroud)

  • 我知道所有这些,但在我的情况下不能使用 readonly,因为我需要它作为 System.ComponentModel.DataAnnotations 的属性。所需属性的 ValidationAttribute ErrorMessage 必须是 const。我知道还有另外 2 个 ValidationAttribute、ErrorMessageResourceName和 ErrorMessageResourceType 来解决问题,但它也对我没有帮助,原因如下: (3认同)