在字符串中使用变量

136

在 PHP 中,我可以执行以下操作:

$name = 'John';
$var = "Hello {$name}";    // => Hello John

在C#中是否有类似的语言结构?

我知道有 String.Format(); 但是我想知道是否可以不调用字符串的函数或方法来完成。

6个回答

304

在 C# 6 中,您可以使用字符串插值

string name = "John";
string result = $"Hello {name}";

Visual Studio中的语法高亮使其易读,所有标记都得到了检查。


好的解决方案。但是为什么要检查所有的标记呢? - Mechandrius

96

在C# 5或更早版本中,此功能不是内置的。
更新:C# 6现在支持字符串插值,请参阅更新的答案。

推荐的方法是使用String.Format

string name = "Scott";
string output = String.Format("Hello {0}", name);

我写了一个名为SmartFormat的小型开源库,它扩展了String.Format,使其能够使用具有名称的占位符(通过反射)。因此,您可以这样做:

string name = "Scott";
string output = Smart.Format("Hello {name}", new{name}); // Results in "Hello Scott".

希望你喜欢它!


2
使用您的反射实现与标准的string.Format相比,会有怎样的性能惩罚? - styfle
1
我看到你在维基上已经有了一个性能页面,看起来非常有前途。干得好! - styfle
是的,我相信性能页面可能回答了你的问题,但我没有运行过“Hello {0}”与“Hello {name}”之间的比较。显然,反射需要更长的时间。但是,使用缓存功能可以提高解析性能,并且可以最小化差异。无论哪种方式,都非常快速! - Scott Rippey
1
这已经不再是事实了。C#6 将其作为一个特性添加进去了。 - Cole Tobin

30
使用以下方法:
1:第一种方法
var count = 123;
var message = $"Rows count is: {count}";

2:第二种方法
var count = 123;
var message = "Rows count is:" + count;

3:第三种方法
var count = 123;
var message = string.Format("Rows count is:{0}", count);

4: 第四种方法
var count = 123;
var message = @"Rows
                count
                is:" + count;

5:第五种方法
var count = 123;
var message = $@"Rows 
                 count 
                 is:{count}";

2
最好添加一条注释,说明为什么选择使用这些方法中的每一个。 - ZombieCode
你如何执行以下代码:var count = 123; var text = "行数为: {count}"; var message = $text; - damichab
显然,方法4和5返回的字符串与1到3完全不同(要将其视为相同的第一种方法应该是$"Rows\n count\n is: {count}";)。 - Selvin

6

在C#5 (-VS2013)之前,您需要调用一个函数/方法。可以是“普通”函数,例如String.Format,也可以是+运算符的重载。

string str = "Hello " + name; // This calls an overload of operator +.

在C#6(VS2015)中,引入了字符串插值功能(如其他答案所述)。

-1

我看到了这个问题和类似的问题,我更喜欢使用内置方法来解决使用值字典填充模板字符串中的占位符的问题。这是我的解决方案,它基于StringFormatter类,该类来自于thread

    public static void ThrowErrorCodeWithPredefinedMessage(Enums.ErrorCode errorCode, Dictionary<string, object> values)
    {
        var str = new StringFormatter(MSG.UserErrorMessages[errorCode]) { Parameters = values};
        var applicationException = new ApplicationException($"{errorCode}", new ApplicationException($"{str.ToString().Replace("@","")}"));
        throw applicationException;
    }

如果消息存在于一个字典中,而调用者没有访问该字典的权限,但调用者只能访问Enums.ErrorCode,并且可以构建参数数组并将其作为参数发送到上述方法。

假设我们有MSG.UserErrorMessages[errorCode]的值是原始的

"The following entry exists in the dump but is not found in @FileName: @entryDumpValue"

此调用的结果

 var messageDictionary = new Dictionary<string, object> {
                    { "FileName", sampleEntity.sourceFile.FileName}, {"entryDumpValue", entryDumpValue }
                };
                ThrowErrorCodeWithPredefinedMessage(Enums.ErrorCode.MissingRefFileEntry, messageDictionary);

The following entry exists in the dump but is not found in cellIdRules.ref: CellBand = L09

这种方法的唯一限制是避免在传递的任何值的内容中使用“@”符号。


.Net中没有内置的StringFormatter类,你在哪里找到它的? - Vitaly
嗨@Vitaly,你是对的,我已经在我的答案中添加了源代码。感谢你指出这一点。 - Michael Bahig

-3

在C#中,您可以像这样将变量定义为字符串:

var varName = data.Values["some var"] as string;


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接