c# - 从资源中声明一个 const 字符串
问题描述
当我从 resx 声明 const 时,出现编译错误。
private const string ERROR_MESSAGE = MyResource.ResourceManager.GetString("resx_key");
我了解为什么会出现此编译消息,但是是否有从资源中声明 const 的技巧?
解决方案
那是因为 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");
推荐阅读
- python - 事件监听器如何在 Python 的 Turtle 模块中工作?为什么即使他们一直在后台收听,他们也不会阻塞?
- r - 在 `caret::rfe()` 中设置 `tuneLength`
- node.js - 对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态。- 谷歌云功能,Vue3
- c++ - 调用者在调用函数 std::_Mutex_base::unlock 之前未能保持锁定
- git - 无法让 git 忽略文件和文件夹
- javascript - Markdown“目录”在角度 8 中不起作用
- python - Django - 计算年龄直到数据库中的某个日期
- c++ - “Cpr”C++ 请求库返回内部错误
- python - 为什么 df.loc[0][0] 在 python pandas 中给出第一秒而不是第一秒
- firebase - 如何将 GCP KMS 与 Firebase 和 Firebase Cloud Functions 一起使用