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

问题描述 投票:0回答:2

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

在我的课堂上我使用:

public static string message (string userName)
{
   return Resource.WebResource.EmailConfirmation
}

问题在于返回内容为“Hello {userName}”而不是“Hello Toto”。

c# variables string-formatting interpolation resource-files
2个回答
31
投票

您不能在资源上下文中使用字符串插值。但是,您可以通过使用

string.Format
来实现您想要的目的。在您的资源文件中写入如下内容:

Hello {0}

然后像下面这样使用它:

public static string message (string userName)
{
   return string.Format(Resource.WebResource.EmailConfirmation, userName);
}

更新

您可以添加任意数量的参数。例如:

Hello {0}, Confirm your email: {1}

然后您可以将其用作:

string.Format(Resource.WebResource.EmailConfirmation
    , userName
    , HtmlEncoder.Default.Encode(link))

0
投票

如果你真的想使用这样的占位符而不是数字(我理解......)那么你可以这样做:

return Resource.WebResource.EmailConfirmation.Replace("{userName}",userName)

您可以保持菊花链。替换您使用的其他占位符的命令。

return Resource.WebResource.EmailConfirmation.Replace("{userName}",userName).Replace("{loginDate}",loginDate).Replace("{notes}",notes)
© www.soinside.com 2019 - 2024. All rights reserved.