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}";也支持表达式,使用$"{(你的表达式)}"

参考博文(我的代码也来源于此,只是修正了下代码而已):https://www.cnblogs.com/hilolin/p/9123970.html#top

posted on 2019-01-15 15:37  nlh774  阅读(1341)  评论(0编辑  收藏  举报