繁体   English   中英

来自资源的变量的字符串插值

[英]String interpolation with variable from resource

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

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

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

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

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

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

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

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

string message = formatter("Apple");

throw new Exception(message);

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

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

我们有FormattableString classFormattableStringFactory
这是如何使用它们

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]' 的水果不存在。”

您格式化的 object 可以是

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM