首页 > 解决方案 > 从资源中声明一个 const 字符串

问题描述

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

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

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

标签: c#resourcesconstantsresx

解决方案


那是因为 aconst必须是编译时间常数。引用 MSDN 文档:

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

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

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

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

因此const,您可以在static readonly这里使用 a 而不是 :

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

推荐阅读