如何在资源文件中使用字符串插值?

Jah*_*ack 8 c# variables interpolation resource-files string-formatting

我想使用资源文件发送电子邮件.在我的资源文件中,我使用了一个变量"EmailConfirmation",其值为"Hello {userName} ..."

在我的班上我用过:

public static string message (string userName)
{
   return Resource.WebResource.EmailConfirmation
}
Run Code Online (Sandbox Code Playgroud)

问题是返回表示"Hello {userName}"而不是"Hello Toto".

Chr*_*tos 15

您无法在资源上下文中使用字符串插值.但是你可以通过利用你可以实现你想要的string.Format.写入您的资源文件,如下所示:

Hello {0}
Run Code Online (Sandbox Code Playgroud)

然后像下面这样使用它:

public static string message (string userName)
{
   return string.Format(Resource.WebResource.EmailConfirmation, userName);
}
Run Code Online (Sandbox Code Playgroud)

更新

您可以根据需要添加任意数量的参数.例如:

Hello {0}, Confirm your email: {1}
Run Code Online (Sandbox Code Playgroud)

然后你可以用它作为:

string.Format(Resource.WebResource.EmailConfirmation
    , userName
    , HtmlEncoder.Default.Encode(link))
Run Code Online (Sandbox Code Playgroud)