在 PHP 中,我可以执行以下操作:
$name = 'John';
$var = "Hello {$name}"; // => Hello John
在C#中是否有类似的语言结构?
我知道有 String.Format();
但是我想知道是否可以不调用字符串的函数或方法来完成。
在 PHP 中,我可以执行以下操作:
$name = 'John';
$var = "Hello {$name}"; // => Hello John
在C#中是否有类似的语言结构?
我知道有 String.Format();
但是我想知道是否可以不调用字符串的函数或方法来完成。
在 C# 6 中,您可以使用字符串插值:
string name = "John";
string result = $"Hello {name}";
Visual Studio中的语法高亮使其易读,所有标记都得到了检查。
在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".
希望你喜欢它!
var count = 123;
var message = $"Rows count is: {count}";
var count = 123;
var message = "Rows count is:" + count;
var count = 123;
var message = string.Format("Rows count is:{0}", count);
var count = 123;
var message = @"Rows
count
is:" + count;
var count = 123;
var message = $@"Rows
count
is:{count}";
var count = 123; var text = "行数为: {count}"; var message = $text;
? - damichab$"Rows\n count\n is: {count}";
)。 - Selvin在C#5 (-VS2013)之前,您需要调用一个函数/方法。可以是“普通”函数,例如String.Format
,也可以是+运算符的重载。
string str = "Hello " + name; // This calls an overload of operator +.
我看到了这个问题和类似的问题,我更喜欢使用内置方法来解决使用值字典填充模板字符串中的占位符的问题。这是我的解决方案,它基于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
这种方法的唯一限制是避免在传递的任何值的内容中使用“@”符号。
在C#中,您可以像这样将变量定义为字符串:
var varName = data.Values["some var"] as string;