【发布时间】: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