这两种语法有什么区别?
在任何情况下都必须使用String.Format而不是复合字符串吗?
Console.WriteLine("{0:d} {0:t}",DateTime.Now);
Console.WriteLine(String.Format("{0:d} {0:t}",DateTime.Now));
答案 0 :(得分:3)
它们之间没有任何区别,因为
Console.WriteLine("{0:d} {0:t}",DateTime.Now);
将通过此重载函数调用String.Format
函数。
public virtual void WriteLine(String format, Object arg0)
{
WriteLine(String.Format(FormatProvider, format, arg0));
}
答案 1 :(得分:0)
我刚刚注意到一种情况,必须使用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语句分配给一个字符串变量。)