当前位置: 移动技术网 > IT编程>开发语言>.net > 【转载】 C#使用String.Format拼接字符串

【转载】 C#使用String.Format拼接字符串

2019年06月04日  | 移动技术网IT编程  | 我要评论

中国女性,玛雅 作品,新疆地震了

在c#程序开发过程中,很多时候会使用字符串拼接,最简单的字符串拼接操作就是所有的字符串使用加号+相加连接起来,但这种代码形式非常不适合代码维护阅读,尤其是拼接字符串语句比较复杂的时候,如拼接sql语句等情况,此时就可考虑使用string.format函数来实现,通过占位符将语句中需要放入变量的位置空出来,而后再用对应的变量值来格式化。

例如,我们要拼接一个sql查询语句,直接拼接的语句如下:

string name = "xxx";
string value = "xxx";   

string sql = "select * from table where  name='" + name + "'  and id in (select orderid from tableb  where value='" + value + "')";

上述语句可读性比较差,可用string.format函数来改良下:

string sql1 = @"select * from table where name='{0}' and id in (select orderid from tableb where value='{1}')";
sql1 = string.format(name,value);

可读性明显增强。

备注:原文转载自博主个人站,原文链接 c#使用string.format拼接字符串_it技术小趣屋

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网