在c#中自动引用字符串 - 在方法中构建?

Dar*_*qer 19 c# string

是否有一些构建方法在c#中的字符串周围添加引号?

Jon*_*eet 30

你的意思是只是添加引号?像这样?

text = "\"" + text + "\"";
Run Code Online (Sandbox Code Playgroud)

?我不知道有一个内置的方法来做到这一点,但如果你想要写一个很容易:

public static string SurroundWithDoubleQuotes(this string text)
{
    return SurroundWith(text, "\"");
}

public static string SurroundWith(this string text, string ends)
{
    return ends + text + ends;
}
Run Code Online (Sandbox Code Playgroud)

这样更通用一点:

text = text.SurroundWithDoubleQuotes();
Run Code Online (Sandbox Code Playgroud)

要么

text = text.SurroundWith("'"); // For single quotes
Run Code Online (Sandbox Code Playgroud)

我不能说我经常需要这么做才能让它值得拥有一个方法......

  • 易于编写,但除非您自己创建库或其他东西,否则必须写入十亿次.或者为这个微不足道的东西引入第三方库.如果它只是在标准库中,那将非常方便. (2认同)

Tho*_*que 10

string quotedString = string.Format("\"{0}\"", originalString);
Run Code Online (Sandbox Code Playgroud)


Jam*_*iec 9

是的,使用连接和转义字符

myString = "\"" + myString + "\"";
Run Code Online (Sandbox Code Playgroud)

也许是一种扩展方法

public static string Quoted(this string str)
{
    return "\"" + str + "\"";
}
Run Code Online (Sandbox Code Playgroud)

用法:

var s = "Hello World"
Console.WriteLine(s.Quoted())
Run Code Online (Sandbox Code Playgroud)


Bal*_*a R 5

否,但您可以编写自己的方法或创建扩展方法

string AddQuotes(string str)
{
    return string.Format("\"{0}\"", str);
}
Run Code Online (Sandbox Code Playgroud)