我目前正在开发 .net 5.0 应用程序。
我需要将带有变量的资源字符串转换为异常消息。
预期结果: 名称为“Apple”的水果不存在。
实际结果: 名称为“错误”的水果不存在。
我在 Translation.resx 中的资源字符串如下所示:
- 名称:我的错误
- 值:名为“{error}”的水果不存在。
我用于解析消息的 C# 代码如下所示:
string formatter(string error) => $"{Translation.MyError}";
string message = formatter("Apple");
throw new Exception(message);
你知道如何解决这个问题吗?
你知道如何将带有变量的资源字符串转换为内插字符串吗?
最佳答案
我们有 FormattableString类和 FormattableStringFactory .
这是如何使用它们
string error = "Apple";
// This comes from your resourse.
string myErrorMessage = "Fruit with name '{0}' does not exist.";
FormattableString s = FormattableStringFactory.Create(myErrorMessage, error);
string message = s.ToString();
但是,您仍然需要更改资源文件以符合 FormattableStringFactory 的预期。您还需要将 System.Runtime.CompilerServices 命名空间添加到您的项目
关于c# - 使用资源中的变量进行字符串插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67157790/