在字符串中C#变量 [英] C# variables in strings
本文介绍了在字符串中C#变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在PHP我可以做到以下几点:
In PHP I can do the following:
$name = 'John';
$var = "Hello {$name}"; // => Hello John
有没有在C#中类似的语言结构?
Is there a similar language construct in C#?
我知道有一个的String.Format();
,但我想知道,如果它可以在不调用一个函数/方法对字符串进行
I know there is String.Format();
but I want to know if it can be done without calling a function/method on the string.
推荐答案
这功能没有内置于C#。
This functionality is not built-in to C#.
推荐的方式做,这将与的String.Format
:
The recommended way to do this would be with String.Format
:
string name = "Scott";
string output = String.Format("Hello {0}", name);
不过,我编写了一个名为 SmartFormat 扩展 <$ C一个小型开放源码库$ C>的String.Format ,以便它可以使用指定的占位符(通过反射)。所以,你可以这样做:
However, I wrote a small open-source library called SmartFormat that extends String.Format
so that it can use named placeholders (via reflection). So, you could do:
string name = "Scott";
string output = Smart.Format("Hello {name}", new{name}); // Results in "Hello Scott".
希望你喜欢它!
这篇关于在字符串中C#变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文