在字符串中使用变量 [英] Using variables inside strings

查看:74
本文介绍了在字符串中使用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  $ name ='John'; 
$ var =你好{$ name}; // =>您好约翰

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



我知道有 String.Format(); ,但是我想知道是否可以在不调用字符串函数/方法的情况下完成它。

解决方案

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

 字符串名称=约翰; 
字符串结果= $ Hello {name};

在Visual Studio中,此语法的突出显示使其具有较高的可读性,并检查了所有标记。 / p>

In PHP I can do the following:

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

Is there a similar language construct in C#?

I know there is String.Format(); but I want to know if it can be done without calling a function/method on the string.

解决方案

In C# 6 you can use string interpolation:

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

The syntax highlighting for this in Visual Studio makes it highly readable and all of the tokens are checked.

这篇关于在字符串中使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆