C#中的String.Format和复合字符串有什么区别?
这两种语法的区别是什么 是否存在必须使用String.Format而不是复合字符串的情况C#中的String.Format和复合字符串有什么区别?,c#,string.format,C#,String.format,这两种语法的区别是什么 是否存在必须使用String.Format而不是复合字符串的情况 Console.WriteLine("{0:d} {0:t}",DateTime.Now); Console.WriteLine(String.Format("{0:d} {0:t}",DateTime.Now)); 他们之间没有任何区别,因为 Console.WriteLine("{0:d} {0:t}",DateTime.Now); 它将通过这个重载函数调用String.Format函数 publi
Console.WriteLine("{0:d} {0:t}",DateTime.Now);
Console.WriteLine(String.Format("{0:d} {0:t}",DateTime.Now));
他们之间没有任何区别,因为
Console.WriteLine("{0:d} {0:t}",DateTime.Now);
它将通过这个重载函数调用String.Format
函数
public virtual void WriteLine(String format, Object arg0)
{
WriteLine(String.Format(FormatProvider, format, arg0));
}
源代码我刚刚注意到一种情况,即必须使用String.Format或插值字符串,而不是普通的复合字符串
SqlConnection myConnection = new SqlConnection("......");
SqlDataAdapter myDataAdapter1 = new SqlDataAdapter("SELECT userAddress FROM tblUserData WHERE userName = '" + userName + "'", myConnection);
SqlDataAdapter myDataAdapter2 = new SqlDataAdapter("SELECT userAddress FROM tblUserData WHERE userName = '{0}'", userName, myConnection);
SqlDataAdapter myDataAdapter3 = new SqlDataAdapter(String.Format("SELECT userAddress FROM tblUserData WHERE userName = '{0}'", userName), myConnection);
SqlDataAdapter myDataAdapter4 = new SqlDataAdapter($"SELECT userAddress FROM tblUserData WHERE userName = '{userName}'",myConnection);
由于参数不正确,myDataAdapter2无法工作
(是的,通常,SELECT语句被分配给一个字符串变量。)您根本不必使用
string.Format
。只需使用插值字符串$“{DateTime.Now}”
Console.WriteLine
在引擎盖下使用String.Format
,因此这两行是相同的。更具体地说,它调用的可能是重复的,然后调用的是String.Format