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

标签 c# string exception resources interpolation

我目前正在开发 .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/

相关文章:

c# - If 语句和 && 或 ||

java - 使用流将映射值收集到字符串

Python .split() 在每个可分割标记栏空白处的字符串上,但忽略一些特定的字符串

ios - Xcode 错误 - 文件中缺少所需的架构 i386

java.rmi.ServerException : RemoteException occurred in server thread (ClassNotFoundException)

java - 将异常消息添加到 json 响应

c# - 使用 Newtonsoft.Json 解析 Json 数组对象

c# - 如何拥有动态 DataTemplateSelector

c# - 引用方法和异常类(c#、.net)

c# - 如何正确发布带有字体文件的 C# Windows 应用程序?