How to use string interpolation in a resource file

2020-04-03 08:07发布

问题:

I would like to use a resource file to send an email. In my resource file I used a variable "EmailConfirmation" with the value "Hello {userName} ... "

In my class I used:

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

The problem is that the return says "Hello {userName}" instead of "Hello Toto".

回答1:

You can't make use of string interpolation in the context of resources. However you could achieve that you want by making use of string.Format. Write to your resource file something like this:

Hello {0}

and then use it like below:

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

Update

You can add as many parameters as you want. For instance:

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

And then you can use it as:

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