C#中$的用法

 1 class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             string tbName = "User";
 6             string colName = "Id";
 7             long id = 5;
 8             string sql1 = string.Format("SELECT * FROM {0} WHERE {1} = {2}", tbName, colName, id);    //值:SELECT * FROM User WHERE Id = 5
 9             Console.WriteLine(sql1);
10             string sql2 = $"SELECT * FROM {tbName} where {colName} = {id}"; //效果同sql1 //SELECT * FROM User WHERE Id = 5
11             Console.WriteLine(sql2);
12 
13             string str1 = "a";
14             string formatStr1 = $"{str1,5}";   //效果同:string.Format("{0,5}", str1);     //值:XXXXa
15             Console.WriteLine(formatStr1); 
16 
17             DateTime dt1 = DateTime.Now;
18             string formatDt1 = $"{dt1:yyyy}";   //效果同:string.Format("{0:yyyy}", dt1);     //值:2019
19             Console.WriteLine(formatDt1);       //2019
20 
21             Console.ReadLine();
22         }
23     }

C#中$的用法:是爲了替代string.format();原先賦值須要佔位符和變量,當須要拼接多個變量會形成語句過長等不易理解問題,$""是爲了替代string.format(),能夠把字符串中的C#變量{}包含起來達到識別C#變量的目的$"{id}";也支持表達式,使用$"{(你的表達式)}"html

參考博文(個人代碼也來源於此,只是修正了下代碼而已):https://www.cnblogs.com/hilolin/p/9123970.html#topsql

相關文章
相關標籤/搜索