使用资源中的变量进行字符串插值

String interpolation with variable from resource

我目前正在开发 .net 5.0 应用程序。

我需要将带有变量的资源字符串转换为异常消息。

预期结果: 名称为 'Apple' 的水果不存在。

实际结果: 水果名称:'error' 不存在。

我在 Translation.resx 中的 资源字符串 如下所示:

我用来解析消息的 C# 代码如下所示:

string formatter(string error) => $"{Translation.MyError}";

string message = formatter("Apple");

throw new Exception(message);

你知道如何解决这个问题吗?

你知道如何将带有变量的资源字符串转换为内插字符串吗?

我们有 FormattableString class and the 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 命名空间添加到您的项目

另一种可能性是 NugetPackage 'ITVComponents.Formatting'。 在 class ITVComponents.Formatting.TextFormat 中有一个扩展方法 FormatText,它允许你做这样的事情:

var tmp = new {error}.FormatText(Translation.MyError);

其中 Translation.MyError 的值为“名称为‘[error]’的水果不存在”。

您格式化的对象可以是

  • 任何类型的对象。那么publicmethods/properties/fields就可以用
  • 一个 IDictionary。然后所有项目都可以通过他们的名字访问

在后台它使用脚本引擎,因此您也可以使用复杂的表达式,例如

"'[error]' has [error.Length] letters, which is an [error.Length%2==0?\"\":\"un\"]-even number."