c# - 如何在 .NET Core 中修复(不抑制)CA1303(不将文字字符串作为本地化参数传递)
问题描述
我有一个简单的值类型MyTestStruct
,它有一个名为的方法Parse
,它试图将字符串转换为MyTestStruct
:
public struct MyTestStruct {
public readonly long UnderlyingValue;
public MyTestStruct(long underlyingValue)
{
UnderlyingValue = underlyingValuel
}
public static MyTestStruct Parse(string input) {
if (string.IsNullOrEmpty(input))
throw new ArgumentException("Value cannot be parsed because the string is either null or empty", nameof(input));
return new MyTestStruct(long.Parse(input));
}
}
VS 2019 向我致以以下警告:
方法“MyTestStruct MyTestStruct.Parse(string input)”将文字字符串作为参数“message”传递给“ArgumentException.ArgumentException(string message, string paramName)”。而是从资源表中检索以下字符串:“无法解析值,因为字符串为空或空”
在线搜索似乎主要集中在抑制警告上,但我宁愿修复它。相反,我希望能够本地化字符串。
一种解决方案是注入IStringLocalizer<MyTestStruct>
,但在结构中有一个额外的依赖项只是“如果出现问题”才使用它似乎有点奇怪。特别是,因为这是不可能的(例如隐式转换、运算符等)。IStringLocalizer<MyTestStruct>
可以是可变的,这通常被认为是不好的做法。
解决此问题的正确方法是什么?
解决方案
您可以在项目的“资源表”中添加字符串文字,并通过程序中的 ResourceManager 实例使用这些文字。如果您使用 Microsoft Visual Studio IDE,这将很容易,如果您使用命令行工具(参考 MS docs CA1303和ResourceManagerClass),则有点困难。在 Visual Studio 解决方案资源管理器中,展开您的项目 > 属性。找到 Resources.resx 文件并双击打开“资源表”。您将看到 3 列 - 名称、值、评论。在名称列中,为您的字符串文字定义一个短名称。在值中,将您的整个字符串文字和您想要的任何相关内容放在注释中。在 Resource 表中设置字符串文字后,您需要创建一个 ResourceManager 对象,定义如下。
// to include the Resources library
using System.Resources;
// Create an instance of ResourceManager class
ResourceManager resourceManager = new ResourceManager("<YourProjectName>.Properties.Resources", typeof(Properties.Resources).Assembly);
// CultureInfo instance to be used for ResourceManager
CultureInfo cultureInfo = CultureInfo.CurrentUICulture;
// Retrieve and assign the string literal value from the Resource table
input = resourceManager.GetString("<Name column value here>", cultureInfo);
推荐阅读
- haskell - 如何将具有两个生成器的列表推导重新表达为两个具有一个生成器的列表推导并获得相同的结果?
- python - 为networkx中的节点分配了错误的颜色
- python - 如何在 Dash,Python 中并排放置下拉菜单
- swift - ObservableObject如何观察Binding值(不是值类型)的变化
- wordpress - 在 Wordpress Gutenberg 中添加 og:image
- python - 仅将一列从字符串转换为 int
- c++ - 尝试更改 void 函数中的指针时引发异常
- php - 如何使重力形式名称字段输入只接受字母
- r - 如何打印神经网络预测概率的混淆矩阵
- html - 引导图标褪色