简体   繁体   English

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

[英]String interpolation with variable from resource

I'm currently working on a .net 5.0 application.我目前正在开发 .net 5.0 应用程序。

I need to transform a Resource String with a variable into an exception message.我需要将带有变量的资源字符串转换为异常消息。

Expected result: Fruit with Name: 'Apple' does not exist.预期结果:名称为“Apple”的水果不存在。

Actual result: Fruit with Name: 'error' does not exist.实际结果:名称为“错误”的水果不存在。

My Resource string in Translation.resx looks like this:我在 Translation.resx 中的资源字符串如下所示:

  • Name: MyError名称:MyError
  • Value: Fruit with name '{error}' does not exist.值:名称为“{error}”的水果不存在。

My C# code to parse the message looks like this:我用于解析消息的 C# 代码如下所示:

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

string message = formatter("Apple");

throw new Exception(message);

Do you know how to solve this issue?你知道如何解决这个问题吗?

Do you know how to transform a resource string with variable into an interpolated string?您知道如何将带有变量的资源字符串转换为插值字符串吗?

We have the FormattableString class and the FormattableStringFactory .我们有FormattableString classFormattableStringFactory
This is how to use them这是如何使用它们

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();

However you still need to change your resources files to be as expected by the FormattableStringFactory.但是,您仍然需要将资源文件更改为 FormattableStringFactory 所期望的。 You need also to add the System.Runtime.CompilerServices namespace to your project您还需要将 System.Runtime.CompilerServices 命名空间添加到您的项目中

Another Possibility would be the NugetPackage 'ITVComponents.Formatting'.另一种可能性是 NugetPackage 'ITVComponents.Formatting'。 In the class ITVComponents.Formatting.TextFormat there's an extension-method FormatText, which allows you to do something like this:在 class ITVComponents.Formatting.TextFormat 中有一个扩展方法 FormatText,它允许您执行以下操作:

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

where Translation.MyError has the value "Fruit with name '[error]' does not exist."其中 Translation.MyError 的值为“名称为 '[error]' 的水果不存在。”

The object you format can either be您格式化的 object 可以是

  • an object of any type.任何类型的 object。 then public methods/properties/fields can be used然后可以使用公共方法/属性/字段
  • an IDictionary<string,object>.一个 IDictionary<string,object>。 then all items can be accessed by their name那么所有项目都可以通过他们的名字来访问

Under the hood it uses a scripting-engine, so you can also use complex expressions such as它在后台使用脚本引擎,因此您还可以使用复杂的表达式,例如

"'[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