【问题标题】:String interpolation with variable from resource来自资源的变量的字符串插值
【发布时间】:2021-07-13 09:38:57
【问题描述】:

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

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

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

实际结果: 名称为“错误”的水果不存在。

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

  • 名称:MyError
  • 值:名称为“{error}”的水果不存在。

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

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

string message = formatter("Apple");

throw new Exception(message);

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

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

【问题讨论】:

  • 您需要使用string.Format(),而不是插值字符串。因此,您的资源字符串将变为 Fruit with name '{0}' does not exist.,而您的调用代码将变为 string.Format(Translation.MyError, error)
  • 谢谢,这显然是唯一的方法:)

标签: c# string exception resources interpolation


【解决方案1】:

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

【讨论】:

  • 谢谢!在我的情况下,它甚至可以在没有 FormattableStringFactory 的情况下工作......
  • 就像@Steve 已经提到的,您仍然需要将您的字符串更改为"Fruit with name '{0}' does not exist"。由于FormattableStringFactory 实际上只不过是string.Format() 的包装,您不妨自己直接调用string.Format()
【解决方案2】:

另一种可能性是 NugetPackage 'ITVComponents.Formatting'。 在 ITVComponents.Formatting.TextFormat 类中有一个扩展方法 FormatText,它允许您执行以下操作:

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

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

你格式化的对象可以是

  • 任何类型的对象。然后可以使用公共方法/属性/字段
  • 一个 IDictionary。那么所有项目都可以通过他们的名字来访问

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

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

【讨论】:

  • 感谢您的提示!我会仔细看看那个:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-17
  • 2015-04-10
  • 2013-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多