String Interpolation With Variable Content in C#

2020-01-29 01:37发布

Can one store the template of a string in a variable and use interpolation on it?

var name = "Joe";
var template = "Hi {name}";

I then want to do something like:

var result = $template;

The reason is my templates will come from a database.

标签: c#
3条回答
Viruses.
2楼-- · 2020-01-29 01:46

This can be done as requested using dynamic compilation, such as through the Microsoft.CodeAnalysis.CSharp.Scripting package. For example:

var name = "Joe";
var template = "Hi {name}";
var result = await CSharpScript.EvaluateAsync<string>(
    "var name = \"" + name + "\"; " +
    "return $\"" + template + "\";");

Note that this approach is slow, and you'd need to add more logic to handle escaping of quotes (and injection attacks) within strings, but the above serves as a proof-of-concept.

查看更多
祖国的老花朵
3楼-- · 2020-01-29 02:01

I guess that these strings will have always the same number of parameters, even if they can change. For example, today template is "Hi {name}", and tomorrow could be "Hello {name}".

Short answer: No, you cannot do what you have proposed.

Alternative 1: use the string.Format method.

You can store in your database something like this:

"Hi {0}"

Then, when you retrieve the string template from the db, you can write:

var template = "Hi {0}"; //retrieved from db
var name = "Joe";
var result = string.Format(template, name);
//now result is "Hi Joe"

With 2 parameters:

var name2a = "Mike";
var name2b = "John";
var template2 = "Hi {0} and {1}!"; //retrieved from db
var result2 = string.Format(template2, name2a, name2b);
//now result2 is "Hi Mike and John!"

Alternative 2: use a placeholder.

You can store in your database something like this:

"Hi {name}"

Then, when you retrieve the string template from the db, you can write:

var template = "Hi {name}"; //retrieved from db
var name = "Joe";
var result = template.Replace("{name}", name);
//now result is "Hi Joe"

With 3 parameters:

var name2a = "Mike";
var name2b = "John";
var template2 = "Hi {name2a} and {name2b}!"; //retrieved from db
var result2 = template2
    .Replace("{name2a}", name2a)
    .Replace("{name2b}", name2b);
//now result2 is "Hi Mike and John!"

Pay attention at which token you choose for your placeholders. Here I used surrounding curly brackets {}. You should find something that is unlikely to cause collisions with the rest of your text. And that depends entirely on your context.

查看更多
够拽才男人
4楼-- · 2020-01-29 02:07

No you can't do that since it needs name value at the time string is created (compile time). Consider using String.Format or String.Replace instead.

查看更多
登录 后发表回答